【问题标题】:Vector of an abstract class that access the derived classes of the abstract one ! How?访问抽象派生类的抽象类的向量!如何?
【发布时间】:2015-04-06 08:36:34
【问题描述】:

实际问题: 有一个从 VAR Class 继承的抽象类操作,然后所有操作派生类(out,sleep,Add)都从操作类继承。 FSM 类也继承自 Var,所以我希望在我的程序中有一个 VAR 类的实例。

我正在尝试将向量 > var 作为 FSM 类和 Operations 类及其偏差之间的共享数据。我通过FSM类在main中初始化了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 的用途是什么?
  • 至于您的问题,您需要查看为什么您需要在调用这些函数的位置调用setLengthgetLength。如果您需要在通用函数或通用函数集中调用这些函数,显然您的设计存在缺陷。
  • 了解downcasting
  • 而且你的长度是静态的,所有方形物体都有相同的长度...
  • 你最好使用shape* element = new sqaure();而不是` shape ** re = new shape*[1];`。

标签: c++ inheritance virtual


【解决方案1】:

并非所有形状都以长度为特征,因此想要获取所有形状的长度是没有意义的。例如,圆可能有半径或直径,但谈论圆的长度会让大多数人一脸茫然。

基类的共同点是它提供了与所有形状相关的功能。因此像 draw() 这样的成员函数可能与所有形状相关(尽管作为虚函数,每个派生类都可以实现其绘制方式的细节),但像 setLength()getLength() 这样的函数可能不相关。

一般来说,当从指向基址的指针开始时,如果需要将其转换为派生类型,这通常被认为是设计失败的标志(而不仅仅是 C++ 从业者)。你真正需要做的是计算出shape 类真正需要提供的一组功能,并使它们足够通用,以便它可以处理一些特殊形状的长度需求,以及其他一些特殊形状的需求形状没有长度。

很难给出比这更具体的答案,因为您的需求(以及您的 shape 类需要提供的一组功能)将特定于您的应用程序。

哦:main() 返回 int,而不是标准 C++ 中的 void。您的编译器可能支持void main(),但并非全部都支持,因此使用它通常被认为是个坏主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 2011-02-01
    • 2018-09-17
    • 1970-01-01
    • 2020-09-01
    • 2018-09-12
    相关资源
    最近更新 更多