c++继承知识点积累:继承和构造函数

1、基类的构造函数不被继承,派生类中需要声明自己的构造函数

 

2、声明构造函数时,只需要对类中新增成员进行初始化,对继承来的基类成员初始化(调用基类的构造函数完成)。

3、派生类的构造函数需要给基类的构造函数传递参数。

 

 例子如下:

#include <iostream>
using namespace std;

class BaseObject{
public:
 BaseObject(int bsobj){
  cout<<"BaseObject(int bsobj)"<<endl;
 }
 ~BaseObject(){

  cout<<"~BaseObject()"<<endl;
 }


};
class DerivedObject{

public:
 DerivedObject(int dobj){

  cout<<"DerivedObject(int dobj)"<<endl;
 }
 ~DerivedObject(){

  cout<<"~Object()"<<endl;
 }
};
class Base
{
public:
 int x_;
 BaseObject baseObj;
 Base(int bb):x_(bb),baseObj(20){

  cout<<"Base(int bb)"<<""<<endl;
 }
 Base(const Base& other):baseObj(other.baseObj),x_(other.x_){//调用拷贝构造函数需要对x_成员进行初始化

 }
 ~Base(){

  cout<<"~Base()"<<endl;
 }
protected:
private:
};
class Derived:public Base
{
public:
 Derived(int a,int b,int c):y_(a),Base(b),obj(c){

  cout<<"Derived(int b,int c)"<<endl;
 }
 Derived(const Derived& other):y_(other.y_),Base(other.y_),obj(other.obj){//调用拷贝构造函数

 }
 ~Derived(){

  cout<<"~Derived()"<<endl;
 }
 int y_;
 DerivedObject obj;
protected:
private:
};
int main(){
 Derived de1(100,200,300);
 Derived de2(de1);
 cout<<de1.x_<<"/:"<<de1.y_<<endl;
 cout<<"de2.y_="<<de2.y_<<endl;
 Base b1(400);
 Base b2(b1);

 cout<<b2.x_<<endl;

 return 0;
}

 

 

 

注意:

(1)需要在构造函数的初始化列表中对成员进行初始化的情况有哪些呀?

1、const成员      例如 :const int n=10;

2、引用成员   int n2=100, int & rn=n2;

3、基类没有默认的构造函数的时候,基类的构造函数要在派生类的构造函数列表中进行调用。

4、类的对象成员没有默认构造函数的时候,只能够在类的构造函数初始化列表中调用该对象的构造函数进行初始化

 (2)派生类的对象的构造次序(析构对象的次序正好相反)

首 先是调用基类对象成员的构造函数,然后是调用基类自身的构造数,其次是调用派生类对象成员的构造函数,最后是调用派生类对象自身的构造函数

 

 

 

//

静态的数据成员只有一份拷贝,并且基类和派生类是共享该拷贝的

 

#include <iostream>
using namespace  std;
class Base
{
public:
 static int b;
protected:
private:
};
int Base::b=10;
class Derived:public Base
{
public:
protected:
private:
};
int main(){
 Derived de;
 cout<<Derived::b<<endl;//推荐使用该方法访问变量
 cout<<de.b<<endl;
 cout<<Base::b<<endl;
 return 0;
}

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值