它用于制作正确初始化的对象数组。
我有没有默认构造函数的C类。我想要一个C类的对象数组。我弄清楚了如何初始化这些对象,然后使用静态方法从C派生一个D类,该方法为D的默认构造函数提供C的参数:
#include <iostream>
using namespace std;
class C {
public:
C(int x) : mData(x) {}
int method() { return mData; }
private:
int mData;
};
void f() {
class D : public C {
public:
D() : C(D::clicker()) {}
private:
static int clicker() {
static int current = 22;
return current++;
}
};
D array[50] ;
cout << "This should be 33: --> " << array[11].method() << endl;
cout << "sizodf(C): " << sizeof(C) << endl;
cout << "sizeof(D): " << sizeof(D) << endl;
return;
}
int main(int, char **) {
f();
return 0;
}
为简单起见,本示例使用一个琐碎的非默认构造函数以及在编译时知道值的情况。将这种技术扩展到希望使用仅在运行时才知道的值初始化对象数组的情况很简单。