Van*_*uan 5 c++ initialization
完全重写了问题。请仔细阅读
请注意不要让您感到困惑:基础构造函数需要指向常量数组的指针。它本身不存储指针,而是存储数据!
我有以下代码:
class Base {
public:
Base(int*);
// added this to explain why I need inheritance
virtual void abstractMethod() = 0;
};
Base::Base(const int *array) {
// just for example
cout << array[0] << endl;
cout << array[1] << endl;
cout << array[2] << endl;
}
class Derived : private Base {
public:
Derived();
void abstractMethod();
};
// who will delete? how to initialize?
Derived::Derived(): Base(new int[3]) {
}
Run Code Online (Sandbox Code Playgroud)
我想对我的派生类的用户隐藏 Base(int*) 构造函数。为此,我需要为该数组提供默认值。
问题是,当我使用这样的初始化列表时:
Derived::Derived(): Base(new int[3]) {
}
Run Code Online (Sandbox Code Playgroud)
数组未初始化并且 Base 构造函数打印一些垃圾。这段代码的另一个问题是:谁来释放那个新数组?
如何在传递给基类之前初始化数组?在 C++ 中可能吗?
我想到了另一个解决方案:
class Int3Array {
int array[3];
public:
Int3Array(int v1, int v2, int v3) {
array[0] = v1;
array[1] = v2;
array[2] = v3;
}
int* getPtr() {
return array;
}
};
Derived::Derived(): Base((Int3Array(1,1,1)).getPtr()) {
}
Run Code Online (Sandbox Code Playgroud)
你怎么认为?是不是也很糟糕呢?