一、包含
Gloam类包含Frabjous类
头文件14-1.h
#include <iostream>
#include <cstring>
using namespace std;
class Frabjous
{
private:
char fab[20];
public:
Frabjous(const char *s="c++") // ;fab(s) {}
{strncpy(fab,s,20-1);fab[20]='\0';}
virtual void tell() {cout<<fab<<endl;}
};
class Gloam
{
private:
int glip;
Frabjous fb;
public:
Gloam(int g=0,const char*s="C++");
Gloam(int g,const Frabjous & f);
//Gloam(const Frabjous & f,int g=0);
void tell();
};
实现文件14-1.c
#include <iostream>
#include "14-1.h"
using namespace std;
Gloam ::Gloam(int g,const char *s)
{
glip=g;
fb=s;
}
Gloam ::Gloam(int g,const Frabjous &f)
//Gloam ::Gloam(const Frabjous &f,int g)
{
glip=g;
fb=f;
}
void Gloam::tell()
{
cout<<"glip:"<<glip;
cout<<",fb:";
fb.tell();
}
应用文件14-1appi.c
#include <iostream>
using namespace std;
#include "14-1.h"
int main()
{
Frabjous A;
A.tell();
Gloam B;
// Gloam C(A,32);
Gloam C(32,A);
B.tell();
C.tell();
return 0;
}
g++ -o 14-1.exe 14-1.c 14-1appi.c
结果:
[root@localhost C]# ./14-1.exe
c++
glip:0,fb:C++
glip:32,fb:c++
[root@localhost C]#
二、 私有继承
头文件14-2.h
#include <iostream>
#include <cstring>
using namespace std;
class Frabjous
{
private:
char fab[20];
public:
Frabjous(const char *s="C..") // ;fab(s) {}
{strncpy(fab,s,20-1);fab[20]='\0';}
virtual void tell() {cout<<fab<<endl;}
};
class Gloam :private Frabjous
{
private:
int glip;
//Frabjous fb;
public:
Gloam(int g=0,const char*s="C++");
Gloam(int g,const Frabjous & f);
//Gloam(const Frabjous & f,int g=0);
void tell();
};
实现文件14-2.c
#include <iostream>
#include "14-2.h"
using namespace std;
Gloam ::Gloam(int g,const char *s):Frabjous(s)
{
glip=g;
//fb=s;
}
Gloam ::Gloam(int g,const Frabjous &f):Frabjous(f)
{
glip=g;
// fb=f;
}
void Gloam::tell()
{
cout<<"glip:"<<glip;
cout<<",fab:";
Frabjous::tell();
}
应用文件 14-2appi.c
#include <iostream>
using namespace std;
#include "14-2.h"
int main()
{
Frabjous A;
Frabjous A1("wengp");
A.tell();
A1.tell();
Gloam B;
// Gloam C(A,32);
Gloam C(32,A1);
B.tell();
C.tell();
return 0;
}
g++ -o 14-2.exe 14-2.c 14-2appi.c
结果:
[root@localhost C]# ./14-2.exe
C..
wengp
glip:0,fab:C++
glip:32,fab:wengp