2013-05-05 48 views
1

这是一个相当复杂的问题。所以我有一个绝对抽象的基类和3个派生类(A,B,C)。使用基类的操作符>>创建派生类

使用std::ifstream& operator>>(std::ifstream& ifs, Base* 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. 
} 
从基础运营商

所以>> I必须调用派生类的功能之一,最终“A”(基本*)会得到一个a,从funcion返回B或C类,和我在一个异构集合中保存'a'。

这可能吗?我如何做到这一点,感觉就像我只是在我需要基类中的派生类和派生类中的基类中创建一个圆。

+1

请参阅:http://stackoverflow.com/questions/1080448/best-practice-for-list-of-polymorphic-objects-in-c – 2013-05-05 16:06:56

+0

谢谢,这似乎与我的问题非常相似。 – SaintHUN 2013-05-05 16:45:01

回答

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'); 
    } 
} 
+0

从此不清楚,但是我确实需要全部3个派生类。 – SaintHUN 2013-05-05 16:20:37

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); 
    } 
    ... 
} 

编辑:您可能需要在原型中使用的引用基类指针:

std::ifstream& operator>>(std::ifstream& ifs, Base *&a){ ... } 
+0

为了调用派生类,我必须将它们放在基类之上,并且在派生类中使用基类,我必须将基类放在派生类之上,这是我的理解。这不会导致问题吗? – SaintHUN 2013-05-05 16:30:48

+0

@SaintHUN如果你需要,也许你可以做[forward declaration](http://stackoverflow.com/questions/553682/when-to-use-forward-declaration)。 – gongzhitaao 2013-05-05 16:33:50

+0

也许我误解了你的问题,但你可以在实现它们之前定义类和它们的成员函数。如果需要,基类成员函数的实现可以使用派生类。在这种特殊情况下我没有看到任何问题,因为您只是将派生对象构造为基指针。 – 2013-05-05 16:38:17

0

我设法使用帮助从这个链接来解决我的问题:thanks Scott Jones

基本上我创建了一个特殊的功能,其全部目的是为了弄清楚它需要哪一类s创建(A,B,C)并将其发回处理。

Base* Deserialize(std::ifstream &ifs) 
{ 
Base *temp; 
std::string what; 
ifs >> what; 
if (what== "A") 
    { 
     temp = new A(); 
     return temp; 
    } 
} 

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

+0

这被称为工厂方法。这是我要建议的模式。 – UpAndAdam 2013-05-06 17:49:52

相关问题