如果我有一个基类和一个派生类,如果我想将多个基类和/或派生类组合在一个容器中,我可以创建一个基类指针 vector 。
例子:
class base
{
}
class derived : public base
{
}
std::vector<base*> group;
但是有没有可能做到以下几点呢?
std::vector<base> group;
即:没有指针,需要 new
ing 和 delete
ing?
编辑:2015 年我还不知道多态性,如果你在 2022 年阅读这个问题,那么值得搜索一些相关信息。
最佳答案
是的,您可以使用 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 constructor
都不是的 derived
被称为 nor getx()
一样的。所以使用vector<base>
的目的实现多态是失败的。因此你不应该使用 vector<base>
& 而更喜欢 vectors
的 smart pointers
或原始指针。
关于基类对象的 C++ vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34383979/