对于继承的对象,构造函数在成员初始化列表中使用类名来调用特定的基类构造函数。对于成员对象,构造函数则使用成员名。
例如:#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();
}
上例中,就是利用类名调用基类的构造函数进行初始化。