为什么当我调用 print() 函数时我的字符串不会输出?

Why won't my string output when I call my print() function?

本文关键字:字符串 我的 输出 函数 调用 print 为什么      更新时间:2023-10-16

我的类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;
}

那是因为你没有在任何地方启动它们

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

你应该把它称为

my_home.print();

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

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

在这里,extPersonType::部分只是告诉编译器功能是类的一部分。当你调用函数时,你已经为类的特定对象调用了它(在你的例子中,my_home ),所以你不应该使用类名。

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

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

我怀疑你可能还需要对addressTypepersonTypedateType基类构造函数做类似的事情。