当前位置: 代码迷 >> 综合 >> C++ 类的继承,基类中的构造函数是谁在调用?
  详细解决方案

C++ 类的继承,基类中的构造函数是谁在调用?

热度:23   发布时间:2024-01-19 15:34:20.0

 

1. 如果父类Animal 中的构造函数 是 protected ,or private, 在main() 中创建父类的对象,就会报错:不能访问构造函数

    任何一个类的构造函数 不可以是 protected  or private ,除非它不需要构造对象,只要需要构造对象就必须设置为public.   

 

2. 父类 Animal, 子类 Bird从父类中继承而来,不管是public,protected,private 哪种继承,父类中的构造函数都被调用,即使父类的构造函数

   是 protected 也能被调用,那是谁在调用?

 

难道子类在构造对象的时候默认的也构造了一个父类的对象,这个父类的对象的初始化需要调用父类的构造函数,因此出现父类的构造函数被调用

问题是父类的构造函数是protected的,父类的对象是怎么访问得到的?

   

   

#include <iostream>
#include <string>
using namespace std;
class Animal
{
protected:
Animal():name("Animal"),age(0),color("White")
{cout<<"Animal 构造函数"<<endl;} // 构造函数
~Animal(){cout<<"Animal 析构函数"<<endl;}
private:
string name;
int age;
string color;
};
// 即使是私有继承 也可以调用父类的构造函数和析构函数
// 
class Bird:private Animal
{
public: 
Bird(){cout<<"Bird 构造函数"<<endl;}
~Bird(){cout<<"Bird 析构函数"<<endl;}
protected:
private:
};
void main()
{
Bird cat;     // ok 
//	Animal wolf;  // 错误 can not access protected member declared in class Animal
}


 

 

 

 

  相关解决方案