c++ - 类模板内的 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...
我不明白为什么我不能使用三元运算符。
解决方案
当&Data::RealTime(loc + name)
您尝试获取一个临时对象的地址时,该地址将立即被破坏(使该指针一文不值)。在 C++ 中,您根本无法获取此类对象的地址。
您需要做的是使用创建一个对象new
,如new Data::RealTime(loc + name)
以后不要忘记delete
对象。
话虽如此,更好的解决方案是根本不使用“原始”非拥有指针,而是使用像std::unique_ptr
.
推荐阅读
- c# - 强制 Teamcity 忽略 .net 项目中的工具版本
- python - 如何拆分、发送和合并 UDP?
- java - 在Java中是否有数据类型的数据类型?
- mongodb - 测试时出现 CircleCI 错误(我认为与 MongoDB 有关)-无法读取 null 的属性“拆分”
- javascript - 是否有机会从 RxJs 'subscribe' 中省略 'next' 部分
- java - 想在硒的xpath中输入一个动态值,同时使用POM(PageFactory)
- html - 跨度导致新行
- python - Python中的重载构造函数点?
- haskell - 如何在 Haskell 的 Parsec 中解析罗马数字?
- html - 布尔玛 div 尺寸继承祖父母的