虚函数2

#include usingnamespace std;

class Shape

{

public:

//若类中含有虚函数

//则会自动生成一张虚函数表

//该表存放的是类中虚函数的入口地址

//该类中会自动增加一个指针(虚函数表指针)

//该指针指向该虚函数表

virtual float area()

{

cout << "Shape::area()" << endl;

return 0;

}

};

#define PI 3.1415926

class Circle: public Shape

{

public:

Circle(float r): m_fR(r)

{

}

//若派生类中存在和基类虚函数A

//函数原型相同的函数B,

//则该派生类函数B默认为虚函数

//并且会使用该派生类函数B的函数地址

//覆盖掉虚函数表中原基类虚函数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)

{

//对象的访问范围受限于其类型

//通过基类的指针或者引用

//来调用虚函数时

//会到虚函数表中的相应位置

//取得该虚函数的入口地址

//从而到该地址去执行函数代码

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;

//派生类对象可以赋值给基类的对象

//    shape = c;

//基类的对象不能赋值给派生类对象

//c = shape;//error

Shape *pShape = &c;

Shape &refShape = c;

// Circle *pCircle = &shape; //error

// Circle &refCircle = shape; //error

#endif

cout << "Hello World!" << endl;

return 0;

}

你可能感兴趣的:(虚函数2)