C++ "this"类属性
C++ "this" class attribute
//C++ Made Easy HD 26 - Introduction to Classes
//Michael LeCompte
#include <iostream>
#include <string>
using namespace std;
class Player {
public:
Player() {
cout << "1st overload" << endl;
}
Player(int Health){
cout << "2nd overload" << endl;
this->health = Health;
}
Player(int Health, int attPow){
cout << "3nd overload" << endl;
this->health = Health;
attackPower = attPow;
}
~Player() {
cout << "Player instance destroyed" << endl;
}
//Mutators
void setHealth(int val) {
health = val;
}
void setAttPow(int val) {
attackPower = val;
}
void setDef(int val) {
defense = val;
}
void setXp(int val) {
xp = val;
}
//Accessors
int healthVal() {
return health;
}
int attPowVal() {
return attackPower;
}
int defVal() {
return defense;
}
int xpVal() {
return xp;
}
private:
int health;
int attackPower;
int defense;
int xp;
};
int main() {
Player player[4] = {Player(2, 5), Player(65, 2), Player(2), Player(1)};
cout << player[0].healthVal() << endl;
cout << player[1].healthVal() << endl;
cout << player[2].healthVal() << endl;
system("pause");
return 0;
}
从上面的代码中,我关注的行是this->health = Health
行。我想知道为什么我需要使用 this->health
而不是 health = Health
.我知道这与我正在使用数组创建新的Player
对象这一事实有关(我正在做一个教程(。我只是不明白为什么它会这样,所以我必须使用this->
或它是如何工作的。谢谢。
你不要使用它。 health = Health;
会起作用。但正确的方法是使用初始化:
Player(int Health) : health(Health) {
// constrcutor code
}
Player(int Health){
cout << "2nd overload" << endl;
this->health = Health;
}
如果你的运行状况名称是标题较低的运行状况,则需要使用 this 指针,因为否则 C++ 不知道要使用类变量,并将使用参数变量。
在您的示例中,C++ 知道要使用 1 个(区别在于标题(,您可以跳过 this 指针。
但健康应该通过命名约定使用较低的标题
您不需要在示例中使用 this->
。这是可选的。如果没有this->
,你的代码将是完全等价的。
C++,不是python。名称查找是这样的,这个>成员总是被认为是没有前缀的,只有当你引入一个本地或函数参数来隐藏它时,它才会被隐藏。(另一种特殊情况是在模板中访问基类成员。
不幸的是,像VTK这样的一些图书馆在他们的风格中制造了这种>噪音的废话,所以它像癌症一样传播。
在您的示例中,没有隐藏,因此没有理由使用前缀。作为单独的说明,在 ctors 中,好的代码将使用 init list 而不是赋值,并使 1-param 版本显式。 对于这些情况,您甚至可以使用与成员相同的参数名称。
我唯一一次使用"this"是当我想明确我指的是什么对象时。 也就是说,我在复制构造函数和赋值运算符中使用"this"。
如果您定义了名为 health
的任何局部变量,那么,为了区分此局部变量和类的数据成员,您需要严格使用指针this
。在其他情况下,使用指针也是一种很好的做法this
但不是必需的。
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 为什么使用 "this" 指针调用派生成员函数?
- C++概念:如何使用'concept'检查模板化结构的属性?
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 通过指向指针数组的指针访问子类的属性
- MSVC是否支持C++11样式的属性而不是__declspec
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 类的C++属性似乎已重新初始化
- C++错误:"error: int aaa::bbb is protected within this context"
- Qt Quick-如何仅从c++代码与qml属性交互
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 用概念检查属性的类型
- C++调用具有 *this 属性的单个帮助程序函数
- 为什么在这种情况下是this->属性而不是this.attribute(C++OOP)?
- 对所有成员函数和属性使用 "this" 是否是一种不良做法?
- 在 POO 属性类中带或不带'this'
- 在成员函数尾部返回类型中使用this和属性
- C++ "this"类属性
- C++"this"实例传递给类中的属性