我的班级extPersonType
继承自其他3个班级。程序编译时没有错误,但由于某种原因,字符串relation
和phoneNumber
不会显示。我要求的所有其他信息都有。我的问题在哪里?
class extPersonType: public personType, public dateType, public addressType
{
public:
extPersonType(string relation = "", string phoneNumber = "", string address = "", string city = "", string state = "", int zipCode = 55555, string first = "", string last = "",
int month = 1, int day = 1, int year = 0001)
: addressType(address, city, state, zipCode), personType(first, last), dateType (month, day, year)
{
}
void print() const;
private:
string relation;
string phoneNumber;
};
void extPersonType::print() const
{
cout << "Relationship: " << relation << endl;
cout << "Phone Number: " << phoneNumber << endl;
addressType::print();
personType::print();
dateType::printDate();
}
/*******
MAIN PROGRAM
*******/
int main()
{
extPersonType my_home("Friend", "555-4567", "5142 Wyatt Road", "North Pole", "AK", 99705, "Jesse", "Alford", 5, 24, 1988);
my_home .extPersonType::print();
return 0;
}
答案 0 :(得分:3)
那是因为你没有在任何地方启动它们
extPersonType(string relation = "", string phoneNumber = "", string address = "", string city = "", string state = "", int zipCode = 55555, string first = "", string last = "", int month = 1, int day = 1, int year = 0001)
: relation (relation), phoneNumber (phoneNumber)// <<<<<<<<<<<< this is missing
addressType(address, city, state, zipCode), personType(first, last), dateType (month, day, year)
{
}
您不应忘记在构造函数
中分配/初始化变量此外,这是推荐,但我不认为继承是必要的。你应该使用作文。
class extPersonType
{
private:
string relation;
string phoneNumber;
addressType address;
personType person_name;
dateType date; // birthday ?
}
答案 1 :(得分:1)
你应该把它称为
my_home.print();
你可能对它的声明方式感到困惑:
void extPersonType::print(){ <..> }
这里extPersonType::
部分告诉编译器函数是类的一部分。当您调用该函数时,您已经为该类的特定对象(在您的情况下为my_home
)调用它,因此您不应该使用类名。
答案 2 :(得分:1)
您实际上并未初始化类成员变量。您需要执行以下操作来初始化relation
和phoneNumber
成员:
extPersonType(string relation = "", string phoneNumber = "", string address = "",
string city = "", string state = "", int zipCode = 55555, string first = "", string last = "",
int month = 1, int day = 1, int year = 0001)
: addressType(address, city, state, zipCode), personType(first, last), dateType (month, day, year),
relation(relation), phoneNumber(phoneNumber) // <== init mmebers
{
}
我怀疑您可能需要对addressType
,personType
和dateType
基类构造函数执行类似操作。