简体   繁体   English

C++ 在成员初始化列表中使用“this”关键字

[英]C++ using 'this' keyword in member initialization list

I was writing an Integer struct我正在写一个整数结构

struct Integer
{
    int value;
    Integer(int value_) : value(_value){ }
};

This works fine but instead I wanted to use value name for the parameter too and this causes a name clash.这工作正常,但我也想为参数使用名称,这会导致名称冲突。 That's why I tried to use this keyword like below这就是为什么我尝试像下面这样使用这个关键字

struct Integer
{
    int value;
    Integer(int value) : this->value(value){ }
};

But I got an error and I don't seem to understand the problem here.但是我遇到了一个错误,我似乎不明白这里的问题。 I would be very happy to learn.我会很高兴学习。 Thanks for your answers.感谢您的回答。

The standard way is to write标准的方法是写

struct Integer
{
    int value;
    Integer(int value) : value(value){ }
};

In the initializer list : value(value) , the first value refers to the member (because that's what a member initializer initializes), while the second value refers to the constructor argument (because that's an expression, and the name in an expression is looked up by the ordinary rules).在初始化列表中: value(value) ,第一个value是指成员(因为这是成员初始化器初始化的),而第二个value是指构造函数参数(因为这是一个表达式,并且查找表达式中的名称按普通规则提高)。

This works fine but instead I wanted to use value name for the parameter too and this causes a name clash.这工作正常,但我也想为参数使用值名称,这会导致名称冲突。

No it doesn't.不,它没有。

Integer(int value) : value(value){ }

This is just fine (if a little confusing to some).这很好(如果对某些人来说有点混乱)。

It is simply not permitted in the language grammar to write this-> there, probably because it would make no sense to specify any other object: the this-> is implicitly done for you.在语言语法中根本不允许写this-> there,可能是因为指定任何其他对象是没有意义的: this->是为您隐式完成的。

As other answers already mentioned, it is not defined in the C++grammer / syntax.正如已经提到的其他答案,它没有在 C++grammer/syntax 中定义。 See it here .在这里看到它。

And there is no need to specify this .并且无需指定this To disambiguate class vs. member you don't use this , you use the scope resoultion operator.要消除不使用this类与成员的歧义,请使用范围解析运算符。

See this (strange) example:看到这个(奇怪的)例子:


#include <iostream>


class A{
public:
    A(int a){
        std::cout << "A("<< a << ")\n";
    }
    A(){
        std::cout << "A()\n";
    }
};

class B : public A
{
public:
    int A;
     B(int a) : A::A(42), A(a)
    {}
};

int main()
{  
    B b = 12;
    std::cout << b.A;
    return 0;
}

And of course this already exists :当然这已经存在

#include <iostream>

class B;

class A{
public:
    A(int a){
        std::cout << "A("<< a << ")\n";
    }
    A(){
        std::cout << "A()\n";
    }
    A(B& b);
};

class B : public A
{
public:
    int A;
     B(int a) : A::A(*this), A(a)
    {}
};

inline A::A(B& b){
    std::cout << "A(B&)\n";
}

int main()
{  
    B b = 12;
    std::cout << b.A;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM