使用基类的运算符>>创建派生类
Using the operator>> of a base class to create a derived class
这是一个相当复杂的问题。所以我有一个绝对抽象的基类,和3个派生类(A, B, C)。
使用std::ifstream& operator>>(std::ifstream& ifs, Base* a)
我有一个像这样设置的文件:
A 5 2
B 2 3
每行以a, B, C开头,告诉我要获得的类的类型,然后是类的实际值。
int a, b;
std::string what;
ifs >> what >> a >> b;
if (what == "A")
{
//create an A class using a, and b.
}
所以从基运算符>>我必须调用派生类函数之一,其中最终'a'(基*)将从函数返回a, B或C类,并且我将'a'保存在异构集合中。
这可能吗?我怎么做呢,感觉就像我只是在做一个圆圈,我需要基类中的派生类和派生类中的基类。
创建一个工厂函数可能更有意义,它可以是Base()的静态成员;
如果你想保持当前的结构,我认为你可以这样解决:
std::ifstream& operator>>(std::ifstream& ifs, Base* a){
// remove whatever object you currently have in a
if(a!=NULL) delete a;
// standard factory
// e.g. read what you need to determine the correct derived class
// and call its constructor
int a, b;
std::string what;
ifs >> what >> a >> b;
if (what == "A")
{
//create an A class using a, and b.
a = new A(a,b);
}
...
}
编辑:您可能需要在原型中使用对Base指针的引用:
std::ifstream& operator>>(std::ifstream& ifs, Base *&a){ ... }
真的需要一个派生类吗?根据你提供的信息和代码,我看不出'A', 'B'和'C'除了类型有什么区别,所以我想出了以下代码:
#include <string>
#include <iostream>
using namespace std;
class foo {
public:
foo(int aa = 0, int bb = 0, int tt = 0)
: a(aa), b(bb), tp(tt) {}
// void set_type(int t) { tp = t; }
protected:
int a, b, tp
};
int main() {
char t;
int a, b;
while (cin >> t >> a >> b) {
foo f(a, b, t-'a');
}
}
我设法用这个链接的帮助解决了我的问题:谢谢Scott Jones
基本上,我创建了一个特殊的函数,它的全部目的是找出需要创建哪个类(a, B, C),并将其发回处理。
Base* Deserialize(std::ifstream &ifs)
{
Base *temp;
std::string what;
ifs >> what;
if (what== "A")
{
temp = new A();
return temp;
}
}
这样做的原因是因为它是基类和派生类之外的一个特殊函数,它可以看到并使用它们
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ