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