#include <iostream>
using namespace std;
/*有时,基类存在重载的构造函数,而搞造函数对类的数据成员进行了初始化,
* 这种情况下,在继承基类时,需要对基类的数据成员进行初始化
*
*/
class Person {
protected: //只能在派生类内部访问protected成员,外部不可访问
bool man;
public: // public权限,可被派生类访问
void CheckPerson();
Person(bool initValue) { //构造函数的重载,带初始值
man = initValue;
cout << "Person constructor" << endl;
}
~Person() {
cout << "~Person deconstructor" << endl;
}
};
void Person::CheckPerson() {
if (man)
cout << "Person is man" << endl;
else
cout << "Person is woman" << endl;
}
class Man: public Person { //public继承,可访问基类public和protected权限的成员
public:
Man() : Person(true) {}; //利用初始化列表,对基类的成员进行初始化(基类重载构造函数需要初始化值)
~Man() {};
};
int main()
{
Man Tom;
Tom.CheckPers
第二十九节 C++ 继承之向基类传递参数
最新推荐文章于 2025-02-19 22:32:45 发布