簡體   English   中英

基類對象的C ++向量

[英]C++ vector of base class objects

如果我有一個基類和一個派生類,如果我想在一個容器中將多個基類和/或派生類組合在一起,則可以創建一個基類指針的向量。

例:

class base
{
}

class derived : public base
{
}

std::vector<base*> group;

但是可以執行以下操作嗎?

std::vector<base> group;

即:如果沒有指針,則需要newdelete

回答中的“是” /“否”注釋或更詳細的解釋就足夠了。

是的,您可以使用vector<base> ,並且編譯器不會為此使用引發任何錯誤。 但是, vector<base>的問題在於它無法實現polymorphism 見下文 :-

#include <iostream>
#include <vector>
using namespace std;

class base
{
    int x, id;
    static int i;
    public:
    base()
    {
        id = ++i;
        cout << "Base constructed: " << id << "\n";
    }
    base (const base &b)
    {
        id = ++i;
        cout << "Base copy constructed: " << id << "\n";
    }
    virtual int& getx()
    {
        cout << "Base getx() called\n";
        return x;
    }
    virtual ~base()
    {
        cout << "Base destroyed: " << id << "\n";
    }
};
int base :: i = 0; 

class derived : public base
{
    int x, id;
    static int j;
    public:
    derived()
    {
        id = ++j;
        cout << "Derived constructed: " << id << "\n";
    }
    derived (const derived& d)
    {
        id = ++j;
        cout << "Derived copy constructed: " << id << "\n";
    }
    virtual int& getx()
    {
        cout << "Derived getx() called\n";
        return x;
    }
    virtual ~derived()
    {
        cout << "Derived destroyed: " << id << "\n";
    }
};
int derived :: j = 0;

int main()
{
    vector<base> v;
    v.emplace_back(derived());
    v[0].getx() = 7;
    cout << "\n\n";
    for (int i=0; i<v.size(); ++i)
    cout << v[i].getx() <<"\n";
    cout << "\n\n";
    return 0;
}
/* Output :-
Base constructed: 1
Derived constructed: 1
Base copy constructed: 2
Derived destroyed: 1
Base destroyed: 1
Base getx() called


Base getx() called
7


Base destroyed: 2
*/

你可以清楚地看到,雖然對象是derived既不是copy constructorderived被稱為也不是getx()一樣。 因此,無法實現使用vector<base>實現多態的目的。 因此,您永遠不要使用vector<base> ,而應該使用smart pointers或原始指針的vectors

您不能執行vector<base> ,但是可以執行vector<unique_ptr<base>>並避免必須手動編寫new或delete。 使用make_unique而不是new,可以自動為您處理delete。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM