c++ - 使用委托(delegate)构造函数重新初始化

标签 c++ delegating-constructor

我有这个类X,使用委托(delegate)构造函数我只想将值ij更改为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,我想将其与 ij 一起初始化。

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 any class-or-decltype that denotes the constructor’s class itself. If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer;

关于c++ - 使用委托(delegate)构造函数重新初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772610/

相关文章:

c++ - 委托(delegate)复制构造函数和常量数据初始化

c++ - C++11 委托(delegate)的 ctors 是否比调用 init 函数的 C++03 ctors 表现更差?

c++ - 如何改进 Tesseract 结果

c++ - Hook : why do we need to VirtualProtect() again to restore permissions?

c++ - 新标准版本的 C++ 中是否曾有过无声的行为变化?

c++ - 如何从子进程获取统计信息以衡量资源利用率?

c++ - MFC结构数组

c++ - 错误 : expression cannot be used as an function