Bla*_*OmN 2 c++ polymorphism class object abstract
这是我的C++程序的一些类.
ElementTerrain.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_ */
Run Code Online (Sandbox Code Playgroud)
Mine.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_ */
Run Code Online (Sandbox Code Playgroud)
Mine.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
}
Run Code Online (Sandbox Code Playgroud)
这是我遇到错误的文件:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我想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() { ... };
};
Run Code Online (Sandbox Code Playgroud)
解决方案:修复签名:
string getElement() const { ... }
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
等等...
C++ 11的override关键字对你有很大的帮助 - 它会指出没有名为getElement要覆盖的非const限定的虚拟成员函数.
| 归档时间: |
|
| 查看次数: |
1881 次 |
| 最近记录: |