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/17373339/

相关文章:

c++ - 如何在模板化对象的 vector 上获取迭代器?

C++错误: no match for 'operator<<' (operand types are

java - 我怎样才能安全地停止我的 "class implements Runnable"?

python - 构造函数(Python)之外的方法中的实例变量 - 为什么以及如何?

c++ - 如何在没有重复代码的情况下处理 getter 的 const/non const 组合?

c++ - 如何为 OGRPoint 和 OGRLineString 注册一个 Boost.Geometry 距离策略?

C++ 为什么我不能在我的类中调用函数

objective-c - 何时使用实例变量,何时使用属性

ruby - 这两个 Ruby 类初始化定义有什么区别?

C++ 调试断言失败 : map/set iterator not dereferencable