鉴于此代码
class Address
{
private:
char * streetName;
int houseNumber;
public:
Address(char* strName, int houseNumber)
{....}
}
class Person
{
protected:
char *name, * phoneNumber;
Address addr;
public:
Person(char* n, char* pN, char* stN, char* hsN): addr(stN,hsN)
{
//...... assign variable for person
}
};
class Officer: public Person
{
private:
double salary;
public:
// How to write the constructor??
Officer(char* _name, char*_phoneNumber, char* _streetName, int _streetNumber, double _salary): .... ????
}
如何编写具有五个输入变量的派生类Officer的构造函数,其中_streetName和_streetNumber将被提供给基类Person中包含的成员对象addr?
答案 0 :(得分:5)
您无法直接在派生的class
初始值设定项列表中设置基本成员。
Officer(char* _name, char*_phoneNumber, char* _streetName,
int _streetNumber, double _salary):
Person(_name, _phoneNumber, _streetName, _streetNumber),
salary(_salary)
答案 1 :(得分:2)
您在Person
课程中看到的方法也适用于此处:
Officer(char* _name, char*_phoneNumber, char* _streetName, int _streetNumber, double _salary):
Person(_name, _phoneNumber, _streetName, _streetNumber) {}
您无法在C ++中初始化父类的成员变量。这些是原因
addr
成员。答案 2 :(得分:1)
您可以像这样调用构造函数:
官员(char * _name,char * _phoneNumber,char * _streetName,int _streetNumber,double _salary): Person(char * _name,char * _phoneNumber,char * _streetName,int _streetNumber),salary(salary){}
答案 3 :(得分:0)
首先你需要知道这位军官也是一个人。 意味着你必须为亲自完成的官员做所有的事情。
所以你的军官构造函数应该在内部调用person的构造函数,如下所示:
Officer(char* _name, char*_phoneNumber, char* _streetName, int _streetNumber, double _salary):Person(_name, _phoneNumber, _streetName, _streetNumber)
现在你还必须构造salary的值。所以你的构造函数变为:
Officer(char* _name, char*_phoneNumber, char* _streetName, int _streetNumber, double _salary):Person(_name, _phoneNumber, _streetName, _streetNumber),salary(_salary)
{}