gpt4 book ai didi

c++ - 初始化器中的 this 关键字用于歧义解决

转载 作者:太空狗 更新时间:2023-10-29 20:37:07 26 4
gpt4 key购买 nike

我遇到了使用具有相同名称的参数初始化成员数据的方法:

class T {
int x;
public:
T(int x) : x(x) {} // assign parameter x to T::x
};

它运行良好。但是当我尝试使用 this 关键字进行显式初始化时,发生错误。

    T(int x) : this->x (x) {}   // error

谁能解释一下错误的原因?

最佳答案

根据member initializer list的语法,这里期望的是一个标识符,而 this->x 不是。

class-or-identifier ( expression-list(optional) )
class-or-identifier - any identifier, class name, or decltype expression that names a non-static data member, a direct or virtual base, or (for delegating constructors) the class itself

正如上面显示的可能的标识符,x(x) 很好并且没有歧义,根本不需要使用 this->

关于c++ - 初始化器中的 this 关键字用于歧义解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35958070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com