更明确地说,当我使用 () 创建对象时尝试访问实例变量时出现编译时错误,但是当我不这样做时,代码会按预期编译和运行。此外,此问题仅适用于默认构造函数。我想了解为什么。
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()'
}