使用“这个” C ++中的关键字 [英] Use of "this" keyword in C++

查看:160
本文介绍了使用“这个” 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) { }

这篇关于使用“这个” C ++中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆