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

时间:2013-05-05 15:57:31

标签: c++ operator-keyword

这是一个非常复杂的问题。所以我有一个绝对的抽象Base类和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.
}

所以从Base运算符>>我必须调用派生类函数之一,其中'a'(Base *)将获得从函数返回的A,B或C类,并且我在异构集合中保存'a'。

这可能吗?我该怎么做,感觉就像我只是在一个圆圈,我需要Base类中的Derived类和Derived类中的Base类。

3 个答案:

答案 0 :(得分:1)

创建工厂函数可能更有意义,它可以是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){ ... }

答案 1 :(得分:0)

真的需要一个派生类吗?根据您提供的信息和代码,我不知道'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');
    }
} 

答案 2 :(得分:0)

我设法使用此链接的帮助解决了我的问题:thanks 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;
   }
}

这个工作的原因是因为这是基类和派生类之外的特殊函数,它可以看到和使用它们。