Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;基类对象的向量_C++ - Fatal编程技术网

C++ C++;基类对象的向量

C++ C++;基类对象的向量,c++,C++,如果我有一个基类和一个派生类,如果我想在一个容器中将多个基类和/或派生类组合在一起,我可以创建一个基类指针向量 例如: class base { } class derived : public base { } std::vector<base*> group; 类基 { } 派生类:公共基 { } std::向量组; 但有可能做到以下几点吗 std::vector<base> group; std::向量组; ie:没有需要newing和deleteing

如果我有一个基类和一个派生类,如果我想在一个容器中将多个基类和/或派生类组合在一起,我可以创建一个基类指针向量

例如:

class base
{
}

class derived : public base
{
}

std::vector<base*> group;
类基
{
}
派生类:公共基
{
}
std::向量组;
但有可能做到以下几点吗

std::vector<base> group;
std::向量组;
ie:没有需要
new
ing和
delete
ing的指针


回答中的“是”/“否”注释或更详细的解释就足够了。

你不能做
vector
,但你可以做
vector
,避免手动编写新的或删除。使用
make_unique
而不是new和delete自动处理。

是的,您可以使用
vector
&编译器不会对此用法产生任何错误。然而,
向量
的问题在于它无法实现多态性。见下文:-

#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
*/
#包括
#包括
使用名称空间std;
阶级基础
{
int x,id;
静态int-i;
公众:
base()
{
id=++i;

不可能。请查阅“对象切片”。@n.m.很有启发性,thanksMake_unique是C++14,不允许您指定自定义删除程序,因此它不是直接替换。YMMV@James:目前流行的实现支持它。而且,当前面的操作是直接
delete
调用时,您不需要自定义deleter。