我正在使用C 11,我想在构造函数的初始化列表中初始化一个对象数组.我找到了一个相关的问题,但它不符合我的需求:
>我希望数组对象的类是不可复制的.
>我希望数组对象的类有一个析构函数.
编译:
class foo {
public:
foo(int& n) : i(n) {}
//~foo() {} // If uncommented, it doesn't compile.
private:
int& i;
// Disable copy constructor and assignment operator.
foo(const foo&) = delete;
foo& operator=(const foo&) = delete;
};
class bar {
public:
bar()
: f{{i}, {i}}
{
}
private:
foo f[2];
int i;
};
不编译:
class foo {
public:
foo(int& n) : i(n) {}
~foo() {} // If uncommented, it doesn't compile.
private:
int& i;
// Disable copy constructor and assignment operator.
foo(const foo&) = delete; // If commented out, it compiles.
foo& operator=(const foo&) = delete;
};
class bar {
public:
bar()
: f{{i}, {i}}
{
}
private:
foo f[2];
int i;
};
我使用g并得到以下错误:
main.cpp: In constructor ‘bar::bar()’:
main.cpp:10:5: error: ‘foo::foo(const foo&)’ is private
main.cpp:17:19: error: within this context
main.cpp:17:19: error: use of deleted function ‘foo::foo(const foo&)’
main.cpp:10:5: error: declared here
如果对象不可复制,为什么会有所不同?