文章目录
- 继承
- 多态
继承
继承的作用是代码复用。派生类自动获得基类的除私有成员外的一切。基类描述一般特性,派生类提供更丰富的属性和行为。在构造派生类时,其基类构造函数先被调用,然后是派生类构造函数。在析构时顺序刚好相反。
// 基类 LinearList
class LinearList{
int *buffer;
int size;
public:
LinearList(int num){
size = (num>10)?num:10;
buffer = new int[size];
}
~LinearList(){
delete []buffer;
}
bool insert(int x, int i); // 线性表第i个元素后插入新元素,返回成功或失败
bool remove(int &x, int i); // 删除线性表第i个元素,返回成功或失败
int element(int i) const; // 返回线性表第i个元素, const表示不会修改调用它的对象的任何非静态成员数据
int search(int x) const; // 查找值为x的元素并返回其序号
int length() const; //返回线性表的长度
};
// 派生类 Queue
class Queue:private LinearList{ // 基类的公有和保护成员均变成派生类的私有成员
public:
bool enQueue(int x){ // 元素x入队,返回操作成功或失败
return insert(x, length());
}
bool deQueue(int &x){ // 元素出队, x带回队头元素
return remove(x, 1);
}
};
// 派生类 Stack
class Stack:private LinearList{
public:
bool push(int x){ // 元素x入栈,返回操作成功或失败
return insert(x, 1);
}
bool pop(int &x){ // 元素出栈,x带回栈顶元素
return remove(x, 1);
}
};
多态
多态的作用是使用一个接口调用多种方法,具体调用哪个函数,是在程序运行时决定的。实现多态,需要在派生类中定义与基类成员函数完全相同的方法签名(返回值、函数名、形参都完全一样)。作用在普通成员函数上,称为重置或覆盖。作用在虚成员函数上,称为实现。虚函数的前面都有virtual关键字,纯虚函数名末尾还有"=0"的标记,纯虚函数仅有定义,没有函数实现,当作接口使用。含有纯虚函数的类称为抽象类,不能创建对象,只能被继承。只有类的成员函数才能是虚函数,静态成员函数不能是虚函数,构造函数不能是虚函数,析构函数可以是虚函数。
#include <iostream>
#include <math.h>
// 基类
class Figure{
public:
virtual double getArea() = 0; // 纯虚函数
}; // 千万不要忘记这个分号
// 派生类 Rectangle
class Rectangle:public Figure{
protected:
double height;
double width;
public:
Rectangle(){}
Rectangle(double height, double width){
this->height = height;
this->width = width;
}
double getArea(){
return height*width;
}
};
// 派生类 Triangle
class Triangle:public Figure{
double la;
double lb;
double lc;
public:
Triangle(double la, double lb, double lc){
this->la = la;
this->lb = lb;
this->lc = lc;
}
double getArea(){
double s = (la+lb+lc)/2.0;
return sqrt(s*(s-la)*(s-lb)*(s-lc));
}
};
// 主函数
void main(){
Figure *figures[2] = {new Triangle(2,3,3), new Rectangle(5,8)};
for(int i=0; i<2; i++){
std::cout << "figures[" << i << "] area=" << figures[i]->getArea() << std::endl;
delete figures[i];
}
}