这是我的第一个问题,所以请善待:)
我正在编写一个程序来接收姓名,姓氏和号码/电子邮件地址,并且必须使用继承从基类n
创建一个类person_with_telephone
。
我已经尝试过,甚至接近但是总会出现那些错误,因为我是C ++的新手,我不知道他们的意思。
以下是相关代码:
Person
忽略空成员函数,稍后会出现这些函数。关于我为什么会得到错误的任何想法:
class Person
{
private:
string m_FirstName, m_LastName, m_email, m_telephone;
public:
Person(const string& firstName, const string& lastName, const string telephone) :
m_FirstName(firstName), m_LastName(lastName), m_telephone(telephone)
{}
string get_name() const
{
return m_FirstName;
}
string get_surname() const
{
return m_LastName;
}
bool has_telephone_p()
{
if (m_telephone == "")
{
return false;
cout << "You have no phone number registered" << endl;
}
else
{
return true;
cout << "Your number is: " << m_telephone << endl;
}
}
string get_telephone() const
{
return m_telephone;
}
bool has_email_p()
{
}
};
class Person_with_telephone: public Person
{
private:
string m_telephone;
public:
Person(const string& telephone) : m_telephone(telephone)
{};
string set_telephone()
{
}
string get_telephone()
{
}
};
感谢您的帮助! :)
答案 0 :(得分:2)
Person_with_telephone
是 Person
。因此,Person_with_telephone
的构造函数也在构造Person
。您没有可以调用的默认构造函数,因此您必须将参数提供给Person
构造函数。
这是语法:
class Int
{
public:
int j;
Int (int q) : j(q) { ; }
};
class IntAndString : public Int
{
public:
std::string t;
IntAndString(int q, std::string s) : Int(q), t(s) { ; }
};
此外,由于某些原因,Person_with_telephone
和Person
都有m_telephone
成员。这将导致你痛苦和困惑的结束。如果他们都应该有这样的成员,请给他们不同的名字。
答案 1 :(得分:0)
看起来你有错误的Person_with_telephone构造函数。它的名字应该是Person_with_telephone。它也应该调用Person的构造函数,因为它没有默认的构造函数。也很奇怪,因为你的Person类有m_telephone字段。试试这个构造函数:
Person_with_telephone(const string& firstName, const string& lastName, const string telephone) : Person(firstName,lastName, telephone), m_telephone(telephone)
{};
也许您需要从Person中删除m_telephone。
答案 2 :(得分:0)
在派生类中你必须显式地调用Base构造函数,如果你不会调用它是隐式的,在这种情况下它将被称为inplicit,当发生这种情况时,默认调用base。在你的基础你已经声明构造函数采用3参数并且默认没有被创建,所以错误说。如果您不希望在语言中调用它,或者调用您在派生初始化列表中定义的那个,则必须在base中创建默认值。