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

 

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

}


 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值