【发布时间】:2015-04-06 08:36:34
【问题描述】:
实际问题: 有一个从 VAR Class 继承的抽象类操作,然后所有操作派生类(out,sleep,Add)都从操作类继承。 FSM 类也继承自 Var,所以我希望在我的程序中有一个 VAR 类的实例。
我正在尝试将向量
每次我们通过类操作调用VAR中的exist函数时,它都会返回它不退出,因为它是空的!我该如何克服这个问题?
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class VAR
{
public:vector<pair<string, int>> var;
VAR()
{}
~VAR(){}
void createVar(string x,int y)
{}
void setVarValue(string& x, int y)
{}
int getVarValue(string x){}
bool exits(string& name)
{}
class operations : virtual public VAR
{
public:
operations()
{}
void virtual excute() = 0;
};
class Out :public virtual operations
{
};
class Add :public virtual operations
{
};
class FSM :public virtual VAR, public virtual transition
{
void intialize()
{
createVar("X", 1);
createVar("Y", 5);
}
};
void main()
{
FSM x;
pair<state, vector<pair<state, int>>> p1;
pair<state, int>p2;
x.intialize();
p2.first.name = "b";
p2.second = 3;
p1.first.name = "a";
p1.second.push_back(p2);
x.trans.push_back(p1);
x.trans[0].first.instructionList.push_back(new Add("X=X+Y"));
x.trans[0].first.instructionList.push_back(new Out("X"));
x.trans[0].first.exec_all();//wrong output cause exist() returns false
}
【问题讨论】:
-
首先,
main()返回int,而不是void。其次,您的shape类需要一个虚拟析构函数,第三,您只需要r.push_back(new square());--re的用途是什么? -
至于您的问题,您需要查看为什么您需要在调用这些函数的位置调用
setLength和getLength。如果您需要在通用函数或通用函数集中调用这些函数,显然您的设计存在缺陷。 -
了解downcasting。
-
而且你的长度是静态的,所有方形物体都有相同的长度...
-
你最好使用
shape* element = new sqaure();而不是` shape ** re = new shape*[1];`。
标签: c++ inheritance virtual