2012-03-25 45 views
0

我有父母和孩子班。他们都是超载>>运营商。我需要从文件(或屏幕)读取父对象,然后将其转换为子对象(或使用指针)。 现在我正在使用集合并获取。如何在流操作符重载函数中使用cust或指针?

ifstream& operator>>(ifstream& ifs, Child& ch) 
{ 
    Parent p;  
    ifs >> ch.field >> p; 
    ch.setCh(p); 
    return(ifs); 
} 

void Ch::setCh(Parent pIn){setField1(pIn.getField1());} 

回答

0

一个可能的解决方案可以看出在这个例子中:

#include <iostream> 
using namespace std; 

class A { 
public: 
    int val; 
    friend istream& operator>>(istream& in, A& a); 
}; 

istream& operator>>(istream& in, A& a) { 
cout << "Calling a::>>\n"; 
in >> a.val; 
return in; 
} 

class B : public A { 
public: 
    int val2; 
    friend istream& operator>>(istream& in, B& b); 
}; 

istream& operator>>(istream& in, B& b) { 
    cout << "Calling b::>>\n"; 
    in >> static_cast<A&>(b); 
    in >> b.val2; 
    return in; 
} 
int main(int argc, char** argv) { 
    B b; 
    cin >> b; 
    cout << b.val << " " << b.val2 << endl; 
    return 0; 
} 
+0

谢谢!它总是小事。我错过了“&”在static_cast (b)。 – nekto 2012-03-25 16:21:44