C++ 纯虚函数

纯虚函数:

和普通的虚函数不一样,纯虚函数无需定义。通过在函数体的位置书写 =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 ****

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值