使用“这个” C ++中的关键字

使用“这个” C ++中的关键字

问题描述:


可能重复:

在C ++中过度使用代码气味

什么时候在C ++中使用this关键字?

有任何理由使用this->

在C ++中,关键字this通常被省略?例如:

In C++, is the keyword "this" usually omitted? For example:

Person::Person(int age) {
    _age = age;
}

而不是:

Person::Person(int age) {
    this->_age = age;
}


并通常省略。它可能需要访问变量,当它们被覆盖在范围内,虽然:

Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:

Person::Person() {
    int age;
    this->age = 1;
}

此外:

Person::Person(int age) {
    _age = age;
}

如果您需要具有相同名称的初始化程序,请使用以下符号:

It is pretty bad style; if you need an initializer with the same name use this notation:

Person::Person(int age) : age(age) { }