gpt4 book ai didi

派生类的 C++ 构造函数,其中基类包含类成员

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:08 26 4
gpt4 key购买 nike

给定这段代码

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?

最佳答案

您不能直接在派生的 class 初始化列表中设置基成员。

Officer(char* _name, char*_phoneNumber, char* _streetName, 
int _streetNumber, double _salary):
Person(_name, _phoneNumber, _streetName, _streetNumber),
salary(_salary)

关于派生类的 C++ 构造函数,其中基类包含类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10650894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com