一.公有继承
1.在声明一个派生类时将基类的继承方式指定为public,称为公有继承。
2.用公有继承方式建立的派生类称为公有派生类,其基类称为公有基类
例,公有继承的测试
#include<iostream>
using namespace std ;
class A
{
public :
void get_XY( )
{
cout << "Enter two numbers of x, y : " ;
cin >> x >> y ;
}
void put_XY( )
{
cout << "x = "<< x << ", y = " << y << '\n' ;
}
protected:
int x, y ;
};
class B : public A
{
public :
int get_S( )
{
return s ;
};
void make_S( )
{
s = x * y ;
}; // 使用基类数据成员x,y
protected:
int s;
};
class C : public B
{
public :
void get_H( )
{
cout << "Enter a number of h : " ;
cin >> h ;
}
int get_V( )
{
return v ;
}
void make_V( )
{
make_S( ); // 使用基类成员函数
v = get_S( ) * h ;
}
protected:
int h, v;
};
int main( )
{ A objA ;
B objB ;
C objC ;
cout << "It is object_A :\n" ;
objA.get_XY( ) ;
objA.put_XY( ) ;
cout << "It is object_B :\n" ;
objB.get_XY( ) ;
objB.make_S( ) ;
cout << "S = " << objB.get_S( ) << endl ;
cout << "It is object_C :\n" ;
objC.get_XY( ) ;
objC.get_H( );
objC.make_V( ) ;
cout << "V = " << objC.get_V( ) << endl ;
return 0; }
二.私有继承
1.在声明一个派生类时将基类的继承方式指定为private,称为私有继承。
2.用私有继承方式建立的派生类称为私有派生类,其基类称为私有基类
例.私有继承的测试
#include<iostream>
using namespace std ;
class A
{
public :
void get_XY( )
{
cout << "Enter two numbers of x and y : " ;
cin >> x >> y ;
}
void put_XY( )
{
cout << "x = "<< x << ", y = " << y << '\n' ;
}
protected:
int x, y ;
};
class B : private A
{
public :
int get_S( )
{
return s ;
}
void make_S( )
{
get_XY( );
s = x * y ;
}
private:
int s ;
};
int main( )
{
B objB ;
cout << "It is object_B :\n" ;
objB.make_S( ) ;
cout << "S = " << objB.get_S( ) << endl ;
return 0;
}
三.保护继承
1.在定义一个派生类时将基类的继承方式指定为protected,称为保护继承。
2.用保护继承方式建立的派生类称为保护派生类,其基类称为受保护的基类简称保护基类。
3.从类的用户角度来看,保护成员等价于私有成员。但有一点与私有成员不同,保护成员可以被派生类的成员函数访问。
4.
#include <iostream>
using namespace std;
class Base //声明基类
{
public: //基类公有成员
void setx(int n)
{
x=n;
}
void showx()
{
cout<<"x="<<x<<endl;
}
protected: //基类保护成员
int getx()
{
return x;
}
private: //基类私有成员
int x;
};
class Derived: protected Base
{
public:
void sety(int n)
{
y=n;
}
int gety()
{
return y;
}
void showy()
{
cout<<"y="<<y<<endl;
}
void set(int m,int n)
{
setx(m); //在Derived中x不可访问
y=n;
}
void show()
{
cout<<"x="<<getx() <<endl;
cout<<"y="<<y<<endl;
}
private:
int y;
};
int main()
{
Derived obj;
obj.sety(20);
obj.showy();
obj.set(30,40);
obj.show();
return 0;
}