Object b()和有什么区别?和对象b ;? [英] What is the difference between Object b(); and Object b;?
本文介绍了Object b()和有什么区别?和对象b ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
更明确地说,当我使用()创建对象时尝试访问实例变量时遇到编译时错误,但是当我不这样做时,代码将按预期进行编译和运行。同样,此问题仅适用于默认构造函数。
我想了解原因。
To be more explicit, I get a compile time error when I try accessing an instance variable when I create an object using (), but when I don't, the code compiles and runs as expected. Also, this problem only applies to the default constructor. I would like to understand why.
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();
声明了一个函数以学生
作为返回类型。它没有像您期望的那样声明该类的对象。
The problem is that Student jack();
declares a function with Student
as a return type. It doesn't declare an object of that class as you expect.
这篇关于Object b()和有什么区别?和对象b ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文