c++中成员对象初始化和类继承初始化

       对于继承的对象,构造函数在成员初始化列表中使用类名来调用特定的基类构造函数。对于成员对象,构造函数则使用成员名。

例如:#ifndef _H_FRABJOUS
#define _H_FRABJOUS
#include<string.h>
class Frabjous
{
private:
    char fab[20];
public:
    Frabjous(const char * s="C++")
    {
        strcpy(fab,s);
    }
    virtual void tell()
    {
        std::cout<<fab;
    }
};
class Gloam
{
private:
    int glip;
    Frabjous fb;
public:
    Gloam(int g=0,const char *s="C++");
    Gloam(int g,const Frabjous & f);
    void tell();
};
#endif



#include<iostream>
#include"Frabjous.h"
using namespace std;
Gloam::Gloam(int g,const char *s):fb(s)
{
     glip=g;

}
Gloam::Gloam(int g,const Frabjous & f):fb(f)        
{
    glip=g;
    

}
void Gloam::tell()
{
    cout<<glip<<endl;
    fb.tell();
}

int main()
{
    Gloam gloam(2,"Vb");
    Frabjous frabjous("Vbb");
    Gloam gloam2(3,  frabjous);
    gloam.tell();
    gloam2.tell();    
    return 0;
}

上例中,就是利用成员名对成员对象进行初始化。

再比如:

#ifndef _H_FRABJOUS2
#define _H_FRABJOUS2
#include<cstring>
class Frabjous
{
private:
    char fab[20];
public:
    Frabjous(const char *s="C++")
    {
        strcpy(fab,s);
    }
    virtual void tell()
    {
        std::cout<<fab;
    }
};
class Gloam:private Frabjous
{
private:
    int glip;
public:
    Gloam(int g=0,const char *s="C++");
    Gloam(int g,const Frabjous & f);
    void tell();
};
#endif



#include<iostream>
#include"Frabjous2.h"
using namespace std;
Gloam::Gloam(int g,const char *s):Frabjous(s)
{
    glip=g;

}
Gloam::Gloam(int g,const Frabjous & f):Frabjous(f)
{
    glip=g;

}
void Gloam::tell()
{
    cout<<glip<<endl;
    Frabjous::tell();
    cout<<endl;
    
}
void main()
{
    Gloam gloam(2,"Vb");
    Frabjous frabjous("Vbb");
    Gloam gloam2(2,"Vbbb");
    gloam.tell();
    gloam2.tell();
}


上例中,就是利用类名调用基类的构造函数进行初始化。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值