0

我的班级extPersonType继承自其他 3 个班级。该程序编译没有错误,但由于某种原因字符串relationphoneNumber没有显示出来。我要求的所有其他信息都可以。我的问题在哪里?

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;
}
4

3 回答 3

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 ?
}
于 2012-10-09T06:48:02.357 回答
1

你应该把它称为

my_home.print();

您可能对它的声明方式感到困惑:

void extPersonType::print(){ <..> }

这里的extPersonType::部分只是告诉编译器函数是类的一部分。当您调用该函数时,您已经为类的特定对象(在您的情况下为my_home)调用它,因此您不应使用类名。

于 2012-10-09T06:41:09.670 回答
1

您实际上并没有初始化您的类成员变量。您需要执行以下操作来初始化relationandphoneNumber成员:

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
{
}

我怀疑您可能还需要对 、 和基类构造函数做类似addressTypepersonType事情dateType

于 2012-10-09T06:48:58.000 回答