![](/img/trans.png)
[英]Vector of shared_ptr of a abstract bass class pointing to derived classes
[英]Vector of an abstract class that access the derived classes of the abstract one ! How?
實際問題:具有從VAR Class繼承的Abstract Class操作,然后所有派生類的操作(out,sleep,Add)都從Operations類繼承。 FSM類也從Var繼承,因此我希望程序中有一個VAR類實例。
我試圖使向量<pair <string,int >> var作為FSM類和Operations類之間的共享數據,並且它與devies偏離。 我通過FSM類在主體中初始化了var。
每次我們通過Class操作在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
}
並非所有形狀都有用長度作為特征,因此想要獲取所有形狀的長度沒有任何意義。 例如,一個圓可能有一個半徑或直徑,但是談論一個圓的長度會使大多數人空白。
基類的通常要點是它提供與所有形狀相關的功能。 因此,諸如draw()的成員函數可能與所有形狀相關(盡管作為虛擬函數,每個派生類都可以實現其繪制方式的細節),但諸如setLength()
和getLength()
類的函數卻可能不相關。
一般而言,當從指向基礎的指針開始時,如果需要將其轉換為派生類型,則通常將其視為破壞設計的標志(而不僅僅是C ++從業人員)。 您真正需要做的是找出shape
類確實需要提供的功能集,並使它們足夠通用,以便可以處理某些特殊形狀具有一定長度的需求,而無需處理某些其他特殊形狀有長度。
很難給出比這更具體的答案,因為您的需求(以及您的shape
類需要提供的功能集)將特定於您的應用程序。
哦: main()
返回int
,在標准C ++中不是void
。 您的編譯器可能支持void main()
,但並非全部都支持,因此使用它通常被認為是一個壞主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.