我的代码有问题。我创建了一个简单的类,该类具有带有默认参数的构造函数。我知道如果不向构造函数传递任何参数,则默认值将接管,否则默认值将被参数覆盖。 这是我班上的代码:
// This class models a person
class Person {
public:
// Constructor
Person(string name = "noname", int age = 0, char gender = 'U')
: name_(name),
age_(age),
gender_(gender) {
}
// Accessor for name_
const string& name() const {
return name_;
}
// Accessor for age_
int age() const {
return age_;
}
// Accessor for gender_
char gender() const {
return gender_;
}
// Mutator for name_
void set_name(const string& name) {
name_ = name;
}
// Mutator for age_
void set_age(int age) {
age_ = age;
}
// Mutator for gender_
void set_gender(char gender) {
gender_ = gender;
}
// Returns a string representation of our person
string ToString() {
ostringstream ss;
// Add our base ToString to the stream
ss << name_ << "\nAge: " << age_ << "\nGender: " << gender_ << endl;
return ss.str();
}
private:
string name_;
int age_;
char gender_;
};
// Program starts here
int main() {
// Create an instance of our base class
Person me("Abraham Lincoln", 56, 'M');
cout << me.ToString() << endl;
// Calls the default constructor.
Person someone;
cout << someone.ToString() << endl;
// This is a pun.
Person sometwo();
cout << sometwo.ToString() << endl;
// This ends our program
return 0;
}
第一个示例使用传入的参数初始化对象。第二个示例创建一个对象,并且由于未传入任何参数,因此默认值将接管。调用toString()函数确实可以确认这一点。现在,当我创建第二个示例时,出现编译错误:
base_main.cpp: In function ‘int main()’:
base_main.cpp:24:19: error: request for member ‘ToString’ in ‘sometwo’, which is of non-class type ‘Person()’
cout << sometwo.ToString() << endl;
^
这是什么?有趣的是,如果我注释掉行// cout << sometwo.ToString() << endl;
,该错误将被删除。因此,问题不在构造函数中。我如何确切地读取此错误?什么是non-class type 'Person()'
?
我知道下面的表格是同义词,它们使用默认参数调用构造函数。第一个只是隐式调用构造函数,而第二个则显式调用构造函数而不传递任何参数。我对吗?
Person person1;
Person person2();