首页 > 解决方案 > 类模板内的 C++ 纯虚拟类

问题描述

我正在尝试将纯虚拟类(DataSource)传递给作为类(dataManager)成员的自定义数据结构(AVLTree);纯虚拟类有两个子 RealTime 和 Simulation 但是我不知道如何实例化它们:

AVLTree.h:

public:
        T& info;
        AVLnode* left;
        AVLnode* right;
        unsigned int leftHeight;
        unsigned int rightHeight;
    public:
        AVLnode(T&);
    };

    template <typename T>
    class AVLTree {
    private:
        AVLnode<T>* startNode;
    public:
        AVLTree(T&);

数据源.h:

class DataSource {
    public: 
        virtual void readData(std::string&) = 0;
    };
}
class RealTime : public DataSource{
 ...
}

class Simulation : public DataSource{
....
}

数据管理器.h:

class DataManager {
    private:
        DataStruct::AVLTree<DataSource*> dataSource;
}

数据管理器.cpp:

DataManager::DataManager(Data::FileType filetype, const std::string& loc, const std::string& name):
    dataSource(filetype == Data::RealTime ? &Data::RealTime(loc + name)) : &Data::Simulation(loc+name){}

我试过让它成为一个函数来确定应该返回的类型,但仍然遇到同样的问题。有谁知道如何解决这个问题,或者可以告诉我一些指示?

非常感谢您的宝贵时间。

编辑:
我已经尝试了以下两种解决方案:

但是,我仍然收到警告:
操作数类型不兼容 (Data::RealTime* 和 Data::Simulation*)

这是更新的代码:

dataSource(filetype == Data::FileType::RealTime ? new Data::RealTime(loc + name) : new Data::Simulation(loc+name))
// error occured in - new Data::Realtime  : (<-here) new Data::Simulation...  

我不明白为什么我不能使用三元运算符。

标签: c++

解决方案


&Data::RealTime(loc + name)您尝试获取一个临时对象的地址时,该地址将立即被破坏(使该指针一文不值)。在 C++ 中,您根本无法获取此类对象的地址。

您需要做的是使用创建一个对象new,如new Data::RealTime(loc + name)

以后不要忘记delete对象。


话虽如此,更好的解决方案是根本不使用“原始”非拥有指针,而是使用像std::unique_ptr.


推荐阅读