我有这个类X
,使用委托(delegate)构造函数我只想将值i
和j
更改为0。是否可以这样做?
class X{
public:
X() = default;
X(int ival, int jval) : i{ ival }, j{ jval } {}
X(int new_i) : i{ new_i }, X(i, 0) {} //error here
private:
int i;
int j;
};
int main()
{
X x{ 345, 54 };
x = X{ 34 }; //annoymous copy changes only the i:member
return 0;
}
编辑:我知道 X(int new_int) : X{new_int, 0}
会起作用,但我想知道如果在列表中再初始化一个变量会出现什么错误。
也许我有另一个 z
,我想将其与 i
和 j
一起初始化。
即X(int new_i) :z{ new_i }, X(new_i, 0) {}
最佳答案
直接使用
X(int new_i) : X(new_i, 0) {}
来自 C++ 标准草案 N3337(强调我的):
12.6.2 Initializing bases and members
6 A
mem-initializer-list
can delegate to another constructor of the constructor’s class using anyclass-or-decltype
that denotes the constructor’s class itself. If amem-initializer-id
designates the constructor’s class, it shall be the onlymem-initializer
;
关于c++ - 使用委托(delegate)构造函数重新初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772610/