事实上,您可以使用以下语法显式访问成员变量(在成员函数内部,而不是特别是构造函数):(this->member_name即与同名的函数参数进行区分)。
除此之外,我认为ClassName::static_member保留该语法是为了访问类外部的静态成员。
然后,当我意识到以下set_2()方法正如人们所期望的那样工作时,我感到很惊讶:
#include <iostream>
struct A {
int x;
// The two following methods seem to act similarly:
void set_1(int x) { this->x = x; }
void set_2(int x) { A::x = x; }
};
int main ()
{
A a;
a.set_1(13);
std::cout << a.x << std::endl;
a.set_2(17);
std::cout << a.x << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
#include <iostream>
struct A {
int x;
// The two following methods seem to act similarly:
void set_1(int x) { this->x = x; }
void set_2(int x) { A::x = x; }
};
int main ()
{
A a;
a.set_1(13);
std::cout << a.x << std::endl;
a.set_2(17);
std::cout << a.x << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
A::x在这种情况下使用作用域运算符 ( ) 是一种良好且有效的做法吗?我个人更喜欢它,而不是使用this->x语法。