C++純虛擬函式和Java中的抽象函式區別
阿新 • • 發佈:2019-01-05
一直我對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();
};
sphere:#include "shape.h" shape::shape() { } shape::~shape() { } void shape::draw() const { cout << "shape draw\n"; }
#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();
}
執行結果: