c++ - Object b(); 有什么区别?和对象 b;?

标签 c++ class instance-variables default-constructor

更明确地说,当我使用 () 创建对象时尝试访问实例变量时出现编译时错误,但当我不这样做时,代码会按预期编译和运行。此外,此问题仅适用于默认构造函数。 我想了解原因。

using namespace std;
#include <iostream>

class Student {

  public:

    int gpa;

    Student() { 
      gpa = 4;
    }

    Student( int x ) { 
      gpa = x; 
    }

};

int main() {

  Student zero;
  Student sally( 2 ); 
  Student jack();

  cout << zero.gpa << endl; //prints 4
  cout << sally.gpa << endl; // prints 2
  cout << jack.gpa << endl; //error: request for member 'gpa' in 'jack', which is of non-class type 'Student()'

}

最佳答案

问题是 Student jack(); 声明了一个以 Student 作为返回类型的函数。它没有像您期望的那样声明该类的对象。

关于c++ - Object b(); 有什么区别?和对象 b;?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40079793/

相关文章:

c++ - opengl 在屏幕上打印文本变量 - 菜单

c# - WPF项目的奇怪行为(类命名)

python - 类变量 : "class list" vs "class boolean"

java - 在类中将关键字 this 与多个构造函数一起使用

ruby - 如何为动态实例变量设置 attr_accessor?

c++ - SFML 平台游戏与 map 图 block 发生碰撞

c++ - 为什么数据没有被正确地写入/读取到这个文件中?

c++ - 从 txt 文件中读取。无法解析信息

objective-c - Cocoa Mac 应用程序的一个大类与几个小类的比较

C++如何直接调用类中定义的方法,其中仅对该类的引用由另一个函数返回