C++纯虚函数和Java中的抽象函数区别

一直我对c++纯虚函数的理解有个误区:纯虚函数是不能给出定义的。果然是学艺不精。c++中的纯虚函数和java中的抽象函数很类似,我把相关概念搞混淆了,这里总结一下:java中的抽象函数是只有函数声明,没有方法体。而c++中的纯虚函数是可以有方法体,也就是说是可以给出定义的,并且,在c++中,子类还可以调用父类的纯虚函数-_-。对于用习惯了java而对c++认识比较少的同学,可能看到这里有点吃惊。所以,c++中的纯虚函数和java中的抽象函数虽然平时的作用看起来可能差不多:都是做为一种模板,让子类必须实现该方法。但是,仔细研究其实java中的抽象函数和c++中的纯虚函数差别还是挺大的。

下面例子:定义了一个shape类做为基类,sphere类和triangle类都继承该类,代码很简单,主要是做个演示:

shape:

#pragma once
#include <iostream>

using namespace std;

class shape
{
public:
	shape();
	virtual void draw() const = 0;
	virtual ~shape();
};

#include "shape.h"


shape::shape()
{
}


shape::~shape()
{
}

void shape::draw() const
{
	cout << "shape draw\n";
}
sphere:

#pragma once
#include "shape.h"
 
class sphere :
	public shape
{
public:
	sphere();
	void draw() const;
	virtual ~sphere();
};


#include "sphere.h"


sphere::sphere()
{
}

void sphere::draw() const
{
	cout << "sphere draw\n";
}

sphere::~sphere()
{
}

triangle:

#pragma once
#include "shape.h"
class triangle :
	public shape
{
public:
	triangle();
	void draw() const;
	virtual ~triangle();
};


#include "triangle.h"


triangle::triangle()
{
}
void triangle::draw() const
{
	cout << "triangle draw\n";
}

triangle::~triangle()
{
}

main:


#include <iostream>
using namespace std;

#include "sphere.h"
#include "triangle.h"

int main(void)
{
	//shape* ps0 = new shape;//错误,因为shape是抽象类,不能被实例化
	shape* ps = new sphere;
	shape* ps1 = new triangle;
	ps->draw();
	ps1->draw();
	//调用sahpe::draw
	ps->shape::draw();
	getchar();

}

运行结果:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值