使用作用域运算符访问非静态成员变量

yol*_*yer 3 c++ scope

事实上,您可以使用以下语法显式访问成员变量(在成员函数内部,而不是特别是构造函数):(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语法。

Eug*_*ene 6

在这种情况下使用A::x是有效的,但我认为this->x更惯用并且更不容易出错(代码的读者可以立即看出它x是该类的成员,而不需要思考它A是什么)。