//1.2继承
#include<bits/stdc++.h>
using namespace std;
class base{//基类或超类
public:
base(){ }
void f(char *s="unknown"){
cout<<"function f() in base call from "<<s<<endl;
h();
}
protected:
void g(char *s="unknown"){
cout<<"function g() in base call from "<<s<<endl;
}
private:
void h(){
cout<<"function h() in base"<<endl;
}
};
class DL_1:public/*说明派生类和基类中的public和protected一致,若为protected,则派生类中,基类的public和protected都变为protected*/
virtual base {//子类或派生类,可以使用基类中protected或public的数据成员和成员函数,不需重复定义,不能使用基类的private!
public:
void f(char *s="unknown"){
cout<<"function f() in DL_1 call from "<<s<<endl;
g("DL_1");
h("DL_1");
}
void h(char *s="unknown"){
cout<<"function h() in DL_1 call from "<<s<<endl;
}
};
/*DL_1是从base中派生出来的类,可以调用base中公有和受保护的成员函数,
而由DL_1派生出来的派生类DL_2可以调用DL_1可以调用的成员函数*/
class DL_2:public virtual base {
public :
void f(char *s="unknown"){
cout<<"function f() in DL_2 call from "<<s<<endl;
g("DL_2");
// h();//error:base::h() is not accessible,不能访问基类私有成员
}
};
class DL_3 :public DL_1, public DL_2{//如果DL_2和DL_3不加关键词virtual,则会产生二义性
public :
void f(char *s="unknown"){
cout<<"function f() in DL_3 call from "<<s<<endl;
g("DL_3");
base::f("DL_3");//前置作用域
DL_1::h("DL_3");
}
};
int main(){
base bc;
DL_1 dl_1;
DL_2 dl_2;
DL_3 dl_3;
bc.f("main(0)");
dl_1.f("main(1)");
dl_1.h("main(1)");
dl_2.f("main(2)");
dl_3.f("main(3)");
}