纯虚函数:
和普通的虚函数不一样,纯虚函数无需定义。通过在函数体的位置书写 =0 就可以将一个虚函数声明为纯虚函数。
注意, virtual void func_null() {} 这也是函数定义,只不过func_null() 是一个空函数而已。纯虚函数没有定义的格式为 virtual void func_null() = 0;
含有纯虚函数的类是抽象类(abstract base class)。抽象类负责定义接口,后续的其他类可以覆盖该接口。C++ 不允许创建一个抽象类的对象。
抽象类的派生类必须重新定义抽象类中声明为纯虚函数的函数,否则这个派生类也是抽象类,同样不能定义对象。
看个例子:
//============================================================================
// Name : pure_virtual_func.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Pure virtual functions test example.
//============================================================================
#include <iostream>
using namespace std;
class Quote {
public:
Quote() = default;
Quote(const std::string &book, double sales_price) :
bookNo(book), price(sales_price) {}
std::string isbn() const {
return bookNo;
}
#if defined (VIRTUAL_FUNC)
virtual double net_price(std::size_t n) const {
return n * price;
}
#else
virtual double net_price(std::size_t n) = 0;
#endif
virtual ~Quote() = default;
private:
std::string bookNo;
protected:
double price;
};
//Quote item;
Quote item("0-123", 1.5);
int main() {
cout << "ISBN:" << item.isbn() << endl;
cout << "Price:" << item.net_price(5) << endl;
// cout << item.bookNo << " " << item.price << endl;
return 0;
}
编译输出:
**** Build of configuration Debug for project pure_virtual_func ****
make all
Building file: ../src/pure_virtual_func.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/pure_virtual_func.d" -MT"src/pure_virtual_func.d" -o "src/pure_virtual_func.o" "../src/pure_virtual_func.cpp"
../src/pure_virtual_func.cpp:14: warning: defaulted and deleted functions only available with -std=c++0x or -std=gnu++0x
../src/pure_virtual_func.cpp:30: warning: defaulted and deleted functions only available with -std=c++0x or -std=gnu++0x
../src/pure_virtual_func.cpp:40: error: cannot declare variable ‘item’ to be of abstract type ‘Quote’
../src/pure_virtual_func.cpp:12: note: because the following virtual functions are pure within ‘Quote’:
../src/pure_virtual_func.cpp:27: note: virtual double Quote::net_price(size_t)
make: *** [src/pure_virtual_func.o] Error 1
**** Build Finished ****