gpt4 book ai didi

C++ 问题 : Cannot allocate an object of abstract type, 但为什么呢?

转载 作者:太空狗 更新时间:2023-10-29 23:35:31 25 4
gpt4 key购买 nike

这是我的 C++ 程序的一些类。

元素地形.h:

#ifndef ELEMENTTERRAIN_H_
#define ELEMENTTERRAIN_H_

#include <iostream>
#include <string>

using namespace std;

class ElementTerrain {
public:
virtual ~ElementTerrain(){}
virtual string getElement() const = 0;
virtual string getType() const = 0;
virtual int getStock() const = 0;
};

#endif /* ELEMENTTERRAIN_H_ */

我的.h:

#ifndef MINE_H_
#define MINE_H_

#include "ElementTerrain.h"

using namespace std;

class Mine : public ElementTerrain{
public:
Mine();
Mine(bool, bool, int);
Mine(const Mine &);
virtual ~Mine();

string getElement(){
return "Mine";
}

string getType(){
if(this->ur == true){
return "UR";}
if(this->plu == true){
return "PLU";}
return "None";
}

int getStock() {
return stock;
}

void setStock(int stock) {
this->stock = stock;
}

bool isUr() {
return ur;
}

bool isPlu() {
return plu;
}

private :
bool ur;
bool plu;
int stock;
};

#endif /* MINE_H_ */

我的.cpp:

#include "Mine.h"

using namespace std;

Mine::Mine() {
this->ur = false;
this->plu = false;
this->stock = 0;
}

Mine::Mine(bool ur, bool plu, int stock){
this->ur=ur;
this->plu=plu;
this->stock = stock;
}

Mine::Mine(const Mine &m){
this->ur=m.ur;
this->plu=m.plu;
this->stock = m.stock;
}

Mine::~Mine() {
// TODO Auto-generated destructor stub
}

这是我出错的文件:

#include "ElementRobot.h"
#include "Mine.h"
#include <iostream>

using namespace std;

bool ElementRobot::RecolteMine(Terrain& t, ElementRobot& r) {
if(t.plateau[x][y]->getElem() != NULL){
if(t.plateau[x][y]->getElem()->getElement() == "Mine"){
Mine *m = new Mine();
if(m.getType() == r.getType() && m.getStock()>0 && r.stock<r.cap){
m.setStock(m.getStock()-1);
t.plateau[x][y]->setElem((Mine) t.plateau[x][y]->getElem());
return true;
}

if(m.getType() == r.getType() && m.getStock()==0){
cout << "Les stocks de cette mine sont épuisés.\n" << endl;
}

if(r.stock==r.cap){
cout << "Votre robot ne peut pas porter plus de minerai.\n" << endl;
}

if(m.getType() != r.getType()){
cout << "Ce robot n'est pas adapté à cette mine.\n" << endl;
}
}}
return false;
}

我想用复制构造函数创建一个 Mine 类型的对象(这里我只尝试使用默认构造函数)但是它说我不能分配一个抽象类型的对象 Mine,即使在我的类 Mine 中没有纯虚方法。我是 C++ 的初学者,我不明白我的错误。我在互联网上也找不到任何东西。

最佳答案

Mine 的成员函数的签名与基类的不匹配(缺少 const 限定符)。因此,您没有重写,而是重载它们并且Mine继续是抽象的而不是可实例化的。

这实际上就像拥有这个:

class Mine {
public:
// this has to be implemented by deriving classes
virtual string getElement() const = 0;

// this is a separate overload
string getElement() { ... };
};

解决方案:修复签名:

string getElement() const { ... }
// ^^^^^

等等……

C++11 的 override关键字会对您有很大帮助 - 它会指出没有名为 getElement 的非 const 限定虚拟成员函数可以覆盖。

关于C++ 问题 : Cannot allocate an object of abstract type, 但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com