C++虛函數(shù)用法示例

一、不加virtual的情況

include <iostream>

using namespace std;

class Shape
{
private:
public:
Shape();
~Shape();
double CalArea();
};

Shape::Shape()
{
cout << "Shape()" << endl;
}

Shape::~Shape()
{
cout << "~Shape()" << endl;
}

double Shape::CalArea()
{
cout << "Shape->CalArea()" << endl;
return 0;
}

//Circle類
class Circle : public Shape
{
private:
double mR; //直徑
public:
Circle(double r);
~Circle();
double CalArea();
};

Circle::Circle(double r)
{
cout << "Circle()" << endl;
mR = r;
}

Circle::~Circle()
{
cout << "~Circle()" << endl;
}

double Circle::CalArea()
{
cout << "Circle->CalArea()" << endl;
return 3.14 * mR * mR;
}

//Rect類
class Rect : public Shape
{
private:
double mW;
double mH;

public:
Rect(double w, double h);
~Rect();
double CalArea();
};

Rect::Rect(double w, double h)
{
cout << "Rect()" << endl;
mW = w;
mH = h;
}

Rect::~Rect()
{
cout << "~Rect()" << endl;
}

double Rect::CalArea()
{
cout << "Rect->CalArea()" << endl;
return mW * mH;
}

int main()
{
Shape *s1 = new Rect(3, 6);
Shape *s2 = new Circle(5);

s1->CalArea();
s2->CalArea();

delete s1;
s1 = NULL;
delete s2;
s2 = NULL;

system("pause");
return 0;

}

運(yùn)行效果:
Shape()
Rect()
Shape()
Circle()
Shape->CalArea()
Shape->CalArea()
~Shape()
~Shape()
請(qǐng)按任意鍵繼續(xù). . .


一、加上virtual關(guān)鍵字

class Shape
{
...
public:
virtual double CalArea(); //父類一定要加virtual
};

class Circle : public Shape
{
...
public:
...
virtual double CalArea(); //子類的virtual可以不加
};
class Rect : public Shape
{
...
public:
...
virtual double CalArea(); //子類的virtual可以不加
};

運(yùn)行效果
Shape()
Rect()
Shape()
Circle()
Rect->CalArea()
Circle->CalArea()
~Shape()
~Shape()
請(qǐng)按任意鍵繼續(xù). . .

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容