使用基类的运算符>>创建派生类

Using the operator>> of a base class to create a derived class

本文关键字:gt 创建 派生 基类 运算符      更新时间:2023-10-16

这是一个相当复杂的问题。所以我有一个绝对抽象的基类,和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;
   }
}

这样做的原因是因为它是基类和派生类之外的一个特殊函数,它可以看到并使用它们