C++ 基类指针和子类指针相互赋值的实现方法

2020-01-06 16:41:03于丽

首先,给出基类animal和子类fish


//============================================================== 
//   animal.h 
// 
// 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; 
} 

一. 基类指针和子类指针之间相互赋值

(1)将子类指针赋值给基类指针时,不需要进行强制类型转换,C++编译器将自动进行类型转换。因为子类对象也是一个基类对象。

(2)将基类指针赋值给子类指针时,需要进行强制类型转换,C++编译器将不自动进行类型转换。因为基类对象不是一个子类对象。子类对象的自增部分是基类不具有的。

执行以下代码,看看会报什么错误:

 


int main(int argc, char* argv[]) 
{ 
 ExamAnimal(); 
 
 return 0; 
} 
 
void ExamAnimal() 
{ 
 // 将子类指针直接赋给基类指针,不需要强制转换,C++编译器自动进行类型转换 
 // 因为fish对象也是一个animal对象 
 animal* pAn; 
 fish* pfh = new fish; 
 pAn = pfh; 
  
 delete pfh; 
 pfh = NULL; 
  
 // 将基类指针直接赋给子类指针,需要强制转换,C++编译器不会自动进行类型转换 
 // 因为animal对象不是一个fish对象 
 fish* fh1; 
 animal* an1 = new animal; 
 // 没有进行强制类型转化 
 fh1 = an1; 
 
 delete an1; 
 an1 = NULL; 
} 

编译时,报如下错误信息:

--------------------Configuration: CPlusPlusPrimer - Win32 Debug-------------------- Compiling... CPlusPlusPrimer.cpp E:StudyexampleCPlusPlusPrimerCPlusPlusPrimer.cpp(94) : error C2440: '=' : cannot convert from 'class animal *' to 'class fish *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast Error executing cl.exe.