久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

C++ 中的向量和多態性

Vectors and polymorphism in C++(C++ 中的向量和多態性)
本文介紹了C++ 中的向量和多態性的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個棘手的情況.它的簡化形式是這樣的

I have a tricky situation. Its simplified form is something like this

class Instruction
{
public:
    virtual void execute() {  }
};

class Add: public Instruction
{
private:
    int a;
    int b;
    int c;
public:
    Add(int x, int y, int z) {a=x;b=y;c=z;}
    void execute() { a = b + c;  }
};

然后在一節課中我做了一些類似的事情......

And then in one class I do something like...

void some_method()
{
    vector<Instruction> v;
    Instruction* i = new Add(1,2,3)
    v.push_back(*i);
}

在另一個班級...

void some_other_method()
{
    Instruction ins = v.back();
    ins.execute();
}

他們以某種方式共享這個指令向量.我關心的是我執行執行"功能的部分.它會起作用嗎?它會保留其 Add 類型嗎?

And they share this Instruction vector somehow. My concern is the part where I do "execute" function. Will it work? Will it retain its Add type?

推薦答案

不,不會.

vector<Instruction> ins;

存儲值,而不是引用.這意味著,無論你如何處理,除了那里的那個 Instruction 對象,它會在未來的某個時候被復制.

stores values, not references. This means that no matter how you but that Instruction object in there, it'll be copied at some point in the future.

此外,由于您使用 new 進行分配,因此上述代碼會泄漏該對象.如果你想正確地做到這一點,你必須這樣做

Furthermore, since you're allocating with new, the above code leaks that object. If you want to do this properly, you'll have to do

vector<Instruction*> ins

或者,更好:

vector< std::reference_wrapper<Instruction> > ins

我喜歡這個這篇博文來解釋reference_wrapper

這種行為稱為對象切片.

這篇關于C++ 中的向量和多態性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

What do compilers do with compile-time branching?(編譯器如何處理編譯時分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 嗎?)
Checking for NULL pointer in C/C++(在 C/C++ 中檢查空指針)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比較運算符的數學式鏈接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之間的區別與“if())
C++, variable declaration in #39;if#39; expression(C++,if 表達式中的變量聲明)
主站蜘蛛池模板: 国产精品毛片一区二区在线看 | 午夜精品一区二区三区在线观看 | 欧美久久久久久久久 | 毛片视频免费观看 | 国产精品夜色一区二区三区 | 国产欧美一区二区三区日本久久久 | 精品九九 | 免费视频成人国产精品网站 | 精品亚洲一区二区三区 | 日韩成人免费视频 | 亚洲成人自拍 | 中文字幕人成乱码在线观看 | 亚洲一区二区三区免费视频 | 一区二区三区精品在线视频 | 久久久国产精品视频 | 亚洲精品视频播放 | 国产精品国产a | 日韩中文字幕区 | 成年人网站在线观看视频 | 精品一级| 91成人免费看片 | 日韩精品在线一区 | 亚洲国产视频一区二区 | 成人午夜影院 | 中文成人在线 | 午夜欧美一区二区三区在线播放 | 久草日韩| 97精品国产 | 人妖无码 | 久草免费在线视频 | 欧美日产国产成人免费图片 | 超碰91在线 | 国产精品视频一二三区 | 免费网站国产 | 欧美日日| 福利在线观看 | 国产精品69久久久久水密桃 | 99久久久国产精品 | 激情欧美一区二区三区中文字幕 | 亚洲一区二区不卡在线观看 | 亚洲天堂av一区 |