为什么一样的写法一个对一个错
#ifndef MOVAB:E_H
#define MOVABLE_H
class Movable{
public:
virtual void move() = 0;
private:
};
#endif
#ifndef BUS_H
#define BUS_H
#include "Movable.h"
#include <iostream>
using namespace std;
class Bus : public Movable{
public:
virtual void move(){
cout << "Bus--move()" << endl;
}
void carry(){
cout << "carry()" << endl;
}
private:
};
#endif
#ifndef TANK_H
#define TANK_H
#include "Movable.h"
#include <iostream>
using namespace std;
class Tank : public Movable{
public:
virtual void move(){
cout << "Tank--move()" << endl;
}
void shot(){
cout << "shot()" << endl;
}
private:
};
#endif
#include <iostream>
using namespace std;
#include "Movable.h"
#include "Bus.h"
#include "Tank.h"
void doSomething(Movable *obj){
obj->move();
if (typeid(*obj) == typeid(Bus)){
Bus *bus = dynamic_cast<Bus *>(obj);
bus->carry();
}
if (typeid(*obj) == typeid(Tank)){
Tank *tank = dynamic_cast<Tank *>(obj);
tank->shot();
}
}
int main(){
Tank tank;
Bus bus;
doSomething(&tank);
return 0;
}请问 一下为什么我用.h头文件的方法编写时错误的,但是用下面这种源文件方法是对的,找了半天也没找到原因。。求大神帮帮忙。。谢谢~祝大家元旦快乐
#include <iostream>
using namespace std;
/**
* 定义移动类:Movable
* 纯虚函数:move
*/
class Movable
{
public:
virtual void move() = 0;
};
/**
* 定义公交车类:Bus
* 公有继承移动类
* 特有方法carry
*/
class Bus : public Movable
{
public:
virtual void move()
{
cout << "Bus -- move" << endl;
}
void carry()
{
cout << "Bus -- carry" << endl;
}
};
/**
* 定义坦克类:Tank
* 公有继承移动类
* 特有方法fire
*/
class Tank :public Movable
{
public:
virtual void move()
{
cout << "Tank -- move" << endl;
}
void shot()
{
cout << "Tank -- shot" << endl;
}
};
/**
* 定义函数doSomething含参数
* 使用dynamic_cast转换类型
*/
void doSomething(Movable *obj)
{
obj->move();
if (typeid(*obj) == typeid(Bus))
{
Bus *bus = dynamic_cast<Bus *>(obj);
bus->carry();
}
if (typeid(*obj) == typeid(Tank))
{
Tank *tank = dynamic_cast<Tank *>(obj);
tank->shot();
}
}
int main(void)
{
Bus b;
Tank t;
doSomething(&b);
doSomething(&t);
return 0;
}