c++ - 我可以通过对象访问类中函数中的变量吗?

标签 c++

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/

相关文章:

c++ - Netbeans 6.8 C++ IDE : program crashes while debugging in cygwin on windows

c++ - 在 C++ 11 中使用函数指针

c# - Windows Mobile 中的 Flash SMS

c++ - 默认情况下,在Visual Studio中从项目中删除安全警告(_CRT_SECURE_NO_WARNINGS)

c++ - 使用双链表的电话簿

c++ - 整数变量与将整数转换为整数之间的结果不同

c++ - IXAudio2 - 0xC0000005 : Access violation writing location 0x00000000

c++ - 变量模板链接失败

c++ - 有没有办法打印当前类中复合数据类型的所有属性

c++ - 重写虚函数不起作用,头文件和 C++ 文件