数组的 C++ 构造函数初始值设定项
C++ Constructor initializer for arrays
我正在使用 C++11,我想在构造函数的初始化列表中初始化一个对象数组。我找到了一个相关的问题,但它不符合我的需求:
- 我希望数组对象的 class 不可复制。
- 我希望数组对象的 class 有一个析构函数。
编译:
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
如果对象是不可复制的,为什么会有所不同?
我正在使用 C++11,我想在构造函数的初始化列表中初始化一个对象数组。我找到了一个相关的问题,但它不符合我的需求:
- 我希望数组对象的 class 不可复制。
- 我希望数组对象的 class 有一个析构函数。
编译:
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
如果对象是不可复制的,为什么会有所不同?