7.2 纯虚函数和抽象类
纯虚函数是在基类中声明的虚函数,它在基类中
没有定义具体的函数体
,而是通过在函数声明的结尾添加= 0来表示。纯虚函数的目的是 为派生类提供一个统一的接口规范
,要求派生类 必须实现
这个函数。
class Base {public:virtual void pureVirtualFunction() = 0;};
#include <iostream>class Base {
protected:int x, y;public:void setxy(int i, int j = 0) {x = i;y = j;}virtual void getarea() = 0; // pure virtual function
};
// square
class Square : public Base {
public:void getarea() {std::cout << "x is " << x << std::endl;std::cout << "suqare area is " << x * x << std::endl;}
};
// rectangle
class Rectangle : public Base {
public:void getarea() {std::cout << "x is " << x << std::endl;std::cout << "y is " << y << std::endl;std::cout << "rectangle area is " << x * y << std::endl;}
};
// cube
class Cube : public Base {
public:void getarea() {std::cout << "x is " << x << std::endl;std::cout << "cube area is " << 6 * x * x << std::endl;}
};int main(int argc, char const *argv[]) {Base *ptr;Square a;Rectangle b;Cube c;ptr = &a;ptr->setxy(4);ptr->getarea();ptr = &b;ptr->setxy(4, 5);ptr->getarea();ptr = &c;ptr->setxy(4);ptr->getarea();
}
x is 4
suqare area is 16
x is 4
y is 5
rectangle area is 20
x is 4
cube area is 96