一、公有继承
基类:
private
protected
public
派生类:
protected
public
private
protected
public
举例
#include<iostream>
using namespace std ;
class A
{ public :
void get_XY() { cout << "Enter two numbers ofx, 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;
};
#include<iostream>
using namespace std ;
class A
{ public :
void get_XY() { cout << "Enter two numbers ofx, 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 ;
}
一、当定义一个基类person(不定义构造函数)时
1、姓名、性别、年龄(访问权限设置为私有)
2、定义公有的成员函数set_p()
3、定义公有的成员函数display_p(),显示person的信息
二、再由基类派生出学生类(不定义构造函数,采用公有继承的方式)
1、增加学号、班级、专业和入学成绩
2、定义公有成员函数set_t()
3、定义成员函定义公有的成员函数display_s(),显示所有的信息
举例
#include<iostream>
#include <string>
using namespace std;
class Person
{
stringname;
intage;
stringsex;
public:
voidset_p() {
cout<<"name\tage\tsex"<<endl;
cin>>name>>age>>sex;
}
voidshow_p() {
cout<<name<<" "<<age<<" "<<sex<<endl;
}
};
class student :public Person
{
stringno;
stringzhuanye;
stringt_class;
floatscore;
public:
voidset_t(){
set_p();//调用继承于基类的成员函数访问继承于基类的私有数据成员
cout<<"zhuanye\tt_class\tscore"<<endl;
cin>>zhuanye>>t_class>>score;
}
voidshow_t() {
show_p();
cout<<zhuanye<<" "<<t_class<<" "<<score<<endl;
}
};