C++ 纯虚函数

781 阅读1分钟

C++纯虚函数(抽象类)

纯虚函数类似JAVA中的抽象类

如果父类有纯虚函数,子类继承时,如果不去实现这个函数,则不能被实例化

没有实现纯虚函数:

#include <iostream>
/**
 * C++纯虚函数(抽象类)
 */

using namespace std;

class Shape {
public:
    Shape();

    ~Shape();

    virtual double calcArea();

    virtual void test()=0;
};

class Circle : Shape {
public:
    Circle(int r);

    ~Circle();


protected:
    int m_r;
};

Circle::Circle(int r) {
    m_r = r;
}

Circle::~Circle() {

}

Shape::Shape() {

}

Shape::~Shape() {

}

double Shape::calcArea() {

}

int main() {
    //纯虚函数
    Circle circle(2); //直接报错,无法编译, 没有实现纯虚函数

    return 0;
}

实现纯虚函数

#include <iostream>
/**
 * C++纯虚函数(抽象类)
 */

using namespace std;

class Shape {
public:
    Shape();

    ~Shape();

    virtual double calcArea();

    virtual void test()=0;
};

class Circle : Shape {
public:
    Circle(int r);

    ~Circle();

    virtual void test();

protected:
    int m_r;
};

Circle::Circle(int r) {
    m_r = r;
}

Circle::~Circle() {

}

void Circle::test() {
    cout << "test()" << endl;
}

Shape::Shape() {

}

Shape::~Shape() {

}

double Shape::calcArea() {

}

int main() {
    //纯虚函数
    Circle circle(2); //实现纯虚函数后 编译执行通过

    return 0;
}