我正在使用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
如果对象不可复制,为什么会有所不同?