[英]initialize a base class pointer with an array of derived class objects
Am I allowed to do the following? 我可以做以下事情吗? To initialize a base class pointer with an array of derived class objects? 要使用派生类对象数组初始化基类指针? The gnu g++ it is crashing when reaching the delete statement ... GNU G ++到达删除语句时崩溃...
Any suggestion? 有什么建议吗? Do I have to overload the new [] and delete operators? 我是否需要重载new []和delete运算符?
Thanks! 谢谢!
#include <iostream>
using std::endl;
using std::cout;
using std::cin;
// base class --> Base
class Base {
public:
// constructor
Base() {
cout << " --> constructor --> Base" << endl;
}
// destructor
virtual ~Base() {
cout << " --> destructor --> ~Base" << endl;
}
};
// derived class --> D1
class D1 : virtual public Base {
public:
// constructor
D1() : Base(), x1(10) {
cout << " --> constructor --> D1" << endl;
}
// destructor
virtual ~D1() {
cout << " --> destructor --> ~D1" << endl;
}
private:
int x1;
};
// the main program
int main()
{
const int DIM = 100;
Base * pb2 = new D1 [DIM];
delete [] pb2;
return 0;
}
This will not work - C arrays do not know about the dynamic size of polymorphic types. 这将行不通-C数组不知道多态类型的动态大小。 If you want to use polymorphism, then you have to use arrays (preferably std::vector
or another standard array, not a C array) of pointers (preferably smart pointers) to the base type. 如果要使用多态性,则必须使用指向基本类型的指针(最好是智能指针)的数组(最好是std::vector
或另一个标准数组,而不是C数组)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.