继承与派生的概念
派生类的声明:
#include<iostream>
using namespace std;
class Base{
int b;
public:
void display(){
cout<<b<<endl;
}
};
class Derived:public Base{
double d;
public:
void show(){
display();
cout<<d<<endl;
}
};
继承方式与访问控制:
1、公有继承方式:
2、保护继承方式:
3、私有继承方式:
6-4-1例题:公有继承——1:
#include<iostream>
using namespace std;
class Base{
private:
int x;
public:
double y;
public:
void setX(int a){
x=a;
}
};
class Derived:public Base{
char z;
public:
void setD(int a,double b,char c){
setX(a);
y=b;
z=c;
//x=a;
}
void show(){
cout<<" "<<y<<" "<<z<<" "<<endl;
}
};
int main(){
Derived d;
d.setX(2);
d.y=6;
d.setD(1,3,'5');
d.show();
return 0;
}
例题6-1 人与学生共有继承关系的访问属性:
#include<iostream>
#include<string.h>
using namespace std;
class Person{
char name[20];
char sex;
int age;
public:
void setPerson(char nm[],char s,int a){
strcpy(name,nm);
sex=s;
age=a;
}
void display(){
cout<<name<<":"<<sex<<","<<age<<"岁\n";
}
};
class Student:public Person{
int number;
double score;
public:
void setStudent(int n,double scr){
number=n;
score=scr;
}
void show(){
cout<<"学号:"<<number<<",分数:"<<score<<endl;
}
};
int main()
{
Student stu;
stu.setPerson("LiJuan",'f',18);
stu.display();
stu.setStudent(20141010,12);
stu.show();
return 0;
}
例题6-2 人与学生类同名成员覆盖
#include<iostream>
#include<cstring>
using namespace std;
class Person{
char name[20];
char sex;
int age;
protected:
void Set(char nm[],char s,int a){
strcpy(name,nm);
sex=s;
age=a;
}
public:
void display()