为什么当我调用 print() 函数时我的字符串不会输出?
Why won't my string output when I call my print() function?
我的类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;
}
那是因为你没有在任何地方启动它们
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
),所以你不应该使用类名。
您实际上并没有初始化类成员变量。 您需要执行以下操作来初始化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
基类构造函数做类似的事情。
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 我的逻辑反转字符串中的元音有什么问题?
- 为什么我的字符串变量没有打印完整的字符串?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 为什么我的子类不继承父类的字符串?
- 为什么我的 cout 在输出中没有显示字符串?
- 为什么在为其分配编号后无法显示我的字符串值?
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 为什么我的驱动程序只读取部分字符串?
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 为什么我得到长度仅为 3 的字符串排列的输出?
- 为什么我的结构在包含字符串时崩溃?
- 如何将我的每个矢量字符串转换为纪元时间日期
- 用字符串初始化我的类的对象
- 我的字符串数组一次打印出前两个字符串
- 当我的 if 语句在字符串中找到空格时,在无限循环中切换
- 解析字符串:我的代码在测试后显然可以工作,但不雅