C++纯虚函数和Java中的抽象函数区别
一直我对c++纯虚函数的理解有个误区:纯虚函数是不能给出定义的。果然是学艺不精。c++中的纯虚函数和java中的抽象函数很类似,我把相关概念搞混淆了,这里总结一下:java中的抽象函数是只有函数声明,没有方法体。而c++中的纯虚函数是可以有方法体,也就是说是可以给出定义的,并且,在c++中,子类还可以调用父类的纯虚函数-_-。对于用习惯了java而对c++认识比较少的同学,可能看到这里有点吃惊。所以,c++中的纯虚函数和java中的抽象函数虽然平时的作用看起来可能差不多:都是做为一种模板,让子类必须实现该方法。但是,仔细研究其实java中的抽象函数和c++中的纯虚函数差别还是挺大的。
下面例子:定义了一个shape类做为基类,sphere类和triangle类都继承该类,代码很简单,主要是做个演示:
shape:
#pragma once
#include 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
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::drawps->shape::draw();getchar();}
运行结果:
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
