类和局部函数变量中的全局变量

Mut*_*thu 1 c++

我尝试了一个c ++程序,我在类中声明了一个名为"a"的int类型的变量.并创建了一个名为"b"的函数,在其中我再次声明了一个名为"a"的变量并为其赋值.函数内的变量"a"被视为局部变量.如果我想将值赋给类定义中存在的变量a(不在函数内部),我该怎么办呢?

#include <iostream>

using namespace std;

class a{
    public:int a;//need to assign value for this "a" inside the function how can i do it
    int b(){
        int a=5;
        a=7;
        cout<<a;
    }
};
int main() {
    a A;
    A.b();
}
Run Code Online (Sandbox Code Playgroud)

Shi*_*mar 7

要访问类变量,您可以使用this关键字.有关'this`关键字的更多解释和了解,您可以访问此处

#include <iostream>

using namespace std;

class a{
    public:int a;//need to assign value for this "a" inside the function how can i do it
    int b(){
        int a=5;
        a=7;
        this->a = 8; // set outer a =8
        cout<< "local variable a: " << a << endl;
        cout<< "class a object variable a: " << this->a << endl;
        return 0;
    }
};
int main() {
    a A;
    A.b();
    cout << "A's variable a: " << A.a << endl; //should print 8
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


oar*_*cas 5

使用this->a.

this 允许您从内部访问实例的成员和方法。

编辑:这是一个学术练习,但一个糟糕的编程实践。只需为类、成员和变量使用不同的名称。

  • ...即使它们被成员函数范围内的某些东西隐藏。 (2认同)