class A
{
int a;
double b;
public:
A(){a=20;B=78.438;}
void data()
{ int num1; num1=a;}
}
我有上面的 CPP 代码。 我可以使用 A 类类型的对象访问“num1”变量吗?
我认为这个问题不同于“How to access variables defined and declared in one function in another function?”。
因为这里我想访问函数中的变量,它是 A 类的成员。我想通过 A 类类型的对象进行访问。
最佳答案
Can I access 'num1' variable using object of class A type?
不,你不能。num1
是在函数 data()
中声明的,因此你无法通过类型 A 的对象访问它。你必须移动声明int num1;
到类主体。:
class A
{
int a;
double b;
public:
int num1;
A(){a=20;B=78.438;}
void data()
{
num1=a;
}
}
现在你可以写:
A a;
a.num1 = 1;
关于c++ - 我可以通过对象访问类中函数中的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36364699/