我尝试了一个 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();
}
最佳答案
要访问类变量,您可以使用 this
关键字。
有关“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;
}
关于c++ - 类内部的全局变量和局部函数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724551/