首先,给出基类animal和子类fish
//==============================================================
// animal.h
//
// begin : 2012-06-30
// author : zwq
// describe: 非虚函数情况下,将子类指针赋给积累指针,验证最终调用
// 基类函数还是子类函数。
//==============================================================
#ifndef ANIMAL_H
#define ANIMAL_H
//===============================================================
//
// animal
// 动物基类
//
//===============================================================
class animal
{
public:
void breathe(); // 非虚函数
};
//===============================================================
//
// animal
// 鱼类,集成于动物基类
//
//===============================================================
class fish : public animal
{
public:
void breathe(); // 非虚函数
};
#endif
#include "StdAfx.h"
#include <iostream>
#include "Animal.h"
using namespace std;
//===============================================================
//
// animal
// 动物基类
//
//===============================================================
void animal::breathe()
{
cout << "animal breathe" << endl;
}
//===============================================================
//
// animal
// 鱼类,继承于动物基类
//
//===============================================================
void fish::breathe()
{
cout << "fish bubble" << endl;
}
二.子类fish指针赋给基类animal指针,非虚函数调用分析
int main(int argc, char* argv[])
{
ExamAnimal();
return 0;
}
void ExamAnimal()
{
// 将子类指针直接赋给基类指针,不需要强制转换,C++编译器自动进行类型转换
// 因为fish对象也是一个animal对象
animal* pAn;
fish* pfh = new fish;
pAn = pfh;
// breathe()函数为非虚函数
// 调用基类的breathe()
pAn->breathe();
delete pfh;
pfh = NULL;
}
当我们构造fish类的对象时,首先要调用animal类的构造函数去构造animal类的构造函数,然后才调用fish类的构造函数完成自身部分的构造,从而拼接出一个完整的fish对象。当我们将fish类对象转换为animal类对象时,该对象就被认为是原对象整个内存模型的上半部分,也就是animal对象的内存部分。当我们利用类型转换后的对象指针去调用它的方法时,自然是调用它所在的内存中的方法。
输出结果如下:
二.基类animal指针赋给子类fish指针,非虚函数调用分析
int main(int argc, char* argv[])
{
ExamAnimal();
return 0;
}
void ExamAnimal()
{
// 将基类指针直接赋给子类指针,需要强制转换,C++编译器不会自动进行类型转换
// 因为animal对象不是一个fish对象
fish* fh1;
animal* an1 = new animal;
// 强制类型转换
fh1 = (fish*)an1;
// breathe()函数为非虚函数
// 调用子类的breathe()
fh1->breathe();
delete an1;
an1 = NULL;
}
将animal类指针强制转换为fish类对象后,已经完整构造出了fish类对象,这时利用fish类指针调用breathe()时,当然是fish类的breathe()函数。
输出结果如下:
三.结论
非虚函数在基类和子类中都存在时,利用哪个类的对象调用非虚函数时,就调用哪个类的非虚函数。
或者,可以这样说,转换后的对象属于哪个类,就调用哪个类的非虚函数!