目录
-
前言:
继承:子类中没有产生新的属性或者行为
派生:子类中产生新的属性和行为
-
继承方式与权限问题
- 公有继承
- 保护继承
- 私有继承
格式:
class 子类名:继承方式 父类名
{
};
class father//父类(基类)
{
public:
protected:
}
class son :public father//子类(派生类)公有继承
{
public:
protected:
}
- 继承方式就是权限限定词
- 父类的私有属性和保护属性不能直接访问
- 私有继承会导致父类无法在孙子类产生任何作用
-
继承中的构造函数
- 父亲的属性通过父类的构造函数初始化
- 子类中的构造函数必须要调用父类中的构造函数,必须采用初始化参数列表的形式
class Kingdom{ public: Kingdom(string str, int data):name(str),age(data){} protected: string name; int age; }; class UK:public Kingdom { public: UK() :Kingdom("李傕",1){} protected: };
- 单继承和多继承:
- 单继承:只有一个父类
- 多继承:两个或者两个以上的父
4.一般不继承很多层,会导致类的臃肿
-
继承中同名问题
(就近原则)
- 数据成员同名:要想调用某个特定的类的数据成员,要用类名限定符号(::)
- 成员数函数同名
- 正常赋值调用
- 非正常赋值调用
-
构造顺序问题
构造和继承顺序想同,析构相反,与初始化参数列表无关
课后作业1:
#include<iostream>
#include<string>
#define PI 3.14
using namespace std;
class shape{
public:
float a,b,r;
void print(){
cout << "面积:" << a*b << "\t" << "周长:" << 2*a+2*b<< endl;
}
void printdata(){
cout << "面积:" << PI*r*r << "\t" << "周长:" << 2 * PI*r << endl;
}
protected:
};
class rect:public shape
{
public:
protected:
};
class circle:public shape
{
public:
protected:
};
int main(){
rect r;
circle c;
cin >> r.a >> r.b >> c.r;
r.print();
c.printdata();
while (1);
return 0;
}
课后作业2:
#include<iostream>
#include<string>
using namespace std;
class teacher{
public:
protected:
};
class master{
public:
master() :name("张三"), age(25), grade(89), height(188), weight(123){}
protected:
string name;
int age;
int grade;
int height;
int weight;
};
class student :public master,public teacher
{
public:
void print(){
cout <<name << "\t" << age << "\t" << grade << "\t" << height << "\t" << weight << endl;
}
protected:
};
int main(){
student j;
j.print();
while (1);
return 0;
}