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

时间:2018-02-10 19:07:58

标签: c++

我尝试了一个c ++程序,其中我声明了一个名为&#34的类型为int的变量; a"在课堂上。并创建了一个名为" 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();
}

4 个答案:

答案 0 :(得分:7)

要访问类变量,您可以使用this关键字。 要获得更多解释并了解&#39; this`关键字,您可以转到here

#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;
}

答案 1 :(得分:4)

使用this

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

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

答案 2 :(得分:2)

指定class - a的限定名称,即:a::a,将会:

a::a=7;

答案 3 :(得分:0)

问题在于缺少this指向类变量的指针。

如果类函数中的局部变量与类变量相同,则必须使用this关键字来区分编译器。

人们倾向于做的一个容易的错误就是当mutator的参数变量具有完全相同的名称时,就像类&#39;变量

#include <iostream>

using namespace std;

class Foo {
    int numberA;
public:
    void setNumberA(int numberA) {
        numberA = numberA; /*Incorrect way, the compiler thinks 
                             you are trying to modify the parameter*/

        this->numberA = numberA; //Correct way
    }
};

在您的情况下,您必须在函数this->a内使用b()

相关问题