unique_ptr不能实例化类,因为它是抽象的



我有一个抽象类(Component)这个类应该属于另一个类(GameObject)。每个GameObject都有一个分量向量

头:

class Component;
class GameObject{
public:
GameObject();
virtual ~GameObject();
void addComponent(std::unique_ptr<Component> component);
void addComponent(Component* component);
void removeComponent(std::unique_ptr<Component> component);
virtual void update();
std::string getInfo();

//return the first component of type T
template<typename T>
T* getComponent(){
for(auto& component : components){
if(dynamic_cast<T*>(component.get())){
return dynamic_cast<T*>(component.get());
}
}
return nullptr;
}
// return the component with the type T
template<typename T>
std::vector<T*> getComponents(){
std::vector<T*> components;
for(auto component : this->components){
if(dynamic_cast<T*>(component)){
components.push_back(dynamic_cast<T*>(component));
}
}
return components;
}

std::vector<std::unique_ptr<Component>> components;
};
class Component
{
private:
public:
Component() = delete;
virtual ~Component() = 0;
virtual std::string getInfo();


//the game object this component is attached to
GameObject* gameObject;

};

源:

std::string GameObject::getInfo() {
std::stringstream ss;
ss << typeid(*this).name();
for (Uint32 i = 0; i < this->components.size(); i++) {
ss << typeid(components[i]).name() << " " << this->components[i]->getInfo();
}
}

void GameObject::addComponent(std::unique_ptr<Component> component) {
components.push_back(std::move(component));
}
void GameObject::addComponent(Component* component) {
components.push_back(std::move(std::make_unique<Component>(*component)));
}
void GameObject::removeComponent(std::unique_ptr<Component> component) {
for (auto it = components.begin(); it != components.end(); it++) {
if (it->get() == component.get()) {
components.erase(it);
return;
}
}
}

错误:不能实例化抽象类。文件:内存行3416

你的问题在这里:

void GameObject::addComponent(Component* component) {
components.push_back(std::move(std::make_unique<Component>(*component)));
}

当你解引用component时,只要编译器知道你仍然只有一个Component,而不是实际的实例化——它不能调用适当的复制构造函数。

解决方法是完全删除这个成员函数。您已经有一个采用std::unique_ptr<Component>的版本,因此要求GameObject的用户在所有情况下提供unique_ptr

相关内容

最新更新