#include usingnamespace std;
class Shape
{
public:
//若類中含有虛函數(shù)
//則會(huì)自動(dòng)生成一張?zhí)摵瘮?shù)表
//該表存放的是類中虛函數(shù)的入口地址
//該類中會(huì)自動(dòng)增加一個(gè)指針(虛函數(shù)表指針)
//該指針指向該虛函數(shù)表
virtual float area()
{
cout << "Shape::area()" << endl;
return 0;
}
};
#define PI 3.1415926
class Circle: public Shape
{
public:
Circle(float r): m_fR(r)
{
}
//若派生類中存在和基類虛函數(shù)A
//函數(shù)原型相同的函數(shù)B凌外,
//則該派生類函數(shù)B默認(rèn)為虛函數(shù)
//并且會(huì)使用該派生類函數(shù)B的函數(shù)地址
//覆蓋掉虛函數(shù)表中原基類虛函數(shù)A的地址
float area()
{
cout << "Circle::area()" << endl;
return PI * m_fR * m_fR;
}
void info()
{
cout << "畫的一首好圓" << endl;
}
private:
float m_fR;
};
class Triangle: public Shape
{
public:
Triangle(float h, float b):m_fH(h)
, m_fBottom(b){}
float area()
{
return m_fH * m_fBottom / 2;
}
private:
float m_fH;
float m_fBottom;
};
void showShapeArea(Shape &shape)
{
//對(duì)象的訪問范圍受限于其類型
//通過基類的指針或者引用
//來調(diào)用虛函數(shù)時(shí)
//會(huì)到虛函數(shù)表中的相應(yīng)位置
//取得該虛函數(shù)的入口地址
//從而到該地址去執(zhí)行函數(shù)代碼
cout << shape.area() << endl;
}
int main()
{
cout << "shape:" << sizeof(Shape) << endl;
Shape shape;
Circle c(2);
Triangle t(3, 4);
showShapeArea(shape);
showShapeArea(c);
showShapeArea(t);
// Shape *pShape = &c;
//? ? pShape->info();? //error
#if 0
char a = '\0';
int b = 1257;
a = b;
b = a;
//派生類對(duì)象可以賦值給基類的對(duì)象
//? ? shape = c;
//基類的對(duì)象不能賦值給派生類對(duì)象
//c = shape;//error
Shape *pShape = &c;
Shape &refShape = c;
// Circle *pCircle = &shape; //error
// Circle &refCircle = shape; //error
#endif
cout << "Hello World!" << endl;
return 0;
}