C++类型检查错误

Ach*_*ara 1 c++ types c++98

我按照上一篇文章中的说明重新编写了代码.

我的头文件

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <typeinfo>
#include "Tour.h"
#include "GuidedTour.h"

using namespace std;
class TourManager {

private:
    vector<Tour *> tours;
    void setupTour();
    string getUserInput();
    string displayMainMenu();
    void displayTourDetails();
    void callDisplayOnEach();
    void addBookingsToTour();

public:
    TourManager();
    void go();
};
Run Code Online (Sandbox Code Playgroud)

然后我有一个函数用tour和guidedTour对象填充"list"向量.

void TourManager::setupTour() {

    tours.push_back(new Tour("FP001", "Fun Park 3 Day Pass", 110.00));
    tours.push_back(new GuidedTour("SK003", "Learn to Ski Adventure Tour", 240.00, "28/07
}

void TourManager::callDisplayOnEach() {

    for (vector<Tour *>::iterator it = tours.begin() ; it != tours.end(); ++it) 
    {
        if(typeid(*it) == typeid(GuidedTour)) 
        {    
            cout << "Guided Tour" << "\n";
        }
        else 
        {
            cout << "NOT Guided Tour : " << typeid(*it).name() << "\n";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我似乎总是回到Tour对象.EG:它总是打印NOT Guided Tour.

我如何归档多态行为?

你能建议吗?(我是C++的新手)我需要使用C++ 98

非常感谢

nij*_*sen 5

这不是多态性的工作原理.

如何实现您想要做的事情

dynamic_cast<T>使用RTTI检查多态类型是否实际是类型T:

GuidedTour * ptr = dynamic_cast<GuidedTour *>(*it);
if(ptr != NULL)
{
    std::cout << "This is a guided tour" << '\n';
}
Run Code Online (Sandbox Code Playgroud)

但是,RTTI需要付出代价; 这些是在运行时执行的检查,会降低您的性能,并且可能根本不支持RTTI.

你通常应该做什么

避免需要知道多态对象的确切类型.提供一个无论如何都能正常工作的界面,并依赖于调用虚拟方法来完成工作.

class Tour
{
    public:
        virtual ~Tour() {}

        virtual void info() const
        {
            std::cout << "This is not a guided tour" << '\n';
        }
};

class GuidedTour : public Tour
{
    public:
        void info() const
        {
            std::cout << "This is a guided tour" << '\n';
        }
};

Tour * tour = new GuidedTour();
tour->info();
delete tour; // here you need the virtual destructor
Run Code Online (Sandbox Code Playgroud)

虽然我们处于最佳状态; 请避免原始指针.即使你被C++ 98绑定,也有非常好的智能指针; 例如shared_ptr,Boost提供了与weak_ptrC++ 11中的类似的东西.