2013-04-20 82 views
3

將一個字符串流傳遞給istream我正在嘗試將一個字符串流傳遞給一個對象(類),該對象具有一個聲明和定義的提取運算符>>。例如,對於在object1重載提取運算符的聲明是使用運算符>>

friend istream& operator >>(istream& in, Object1& input); 

在對象2,我的聲明幾乎是相同的

friend istream& operator >>(istream& in, Object2& input); 

在object1提取功能中,func。得到一條線,將它變成一個串流並嘗試使用Object2的提取(>>)運算符。

istream& operator >>(istream& in, Object1& input){ 
    Object2 secondObj; 
    string data; 
    string token; 
    in>>data; 
    in.ignore(); 
    token = GetToken(data, ' ', someint); //This is designed to take a part of data 
    stringstream ss(token); // I copied token into ss 
    ss >> secondObj; // This is where I run into problems. 
} 

我收到錯誤No match for operator >>。這是因爲我需要將stringstream轉換爲istream嗎?如果是這樣,我該怎麼做?

最小的程序是這樣的:在 main.cpp中:

在Object1.h
#include "Object1.h" 
#include "Object2.h" 
#include "dataClass.h" 
using namespace std; 
int main(){ 
    Object1<dataClass> firstObj; 
    cin>>firstObj; 
    cout<<firstObj<<endl; 
} 

#ifdef OBJECT1_H_ 
#define OBJECT1_H_ 
#include <iostream> 
#include <string> 
#include <cstddef> 
#include "Object2.h" 
template<class T> 
class Object1{ 
public: 
    //Assume I made the Big 3 
    template<class U>friend istream& operator >>(istream& in, Object1<U>& input); 
    template<class U>friend ostream& operator <<(ostream& out, const Object1<U>& output); 
private: 
    Object2<T>* head; 
}; 
template<class T> 
istream& operator >>(istream& in, Object1<T>& input){ 
    Object2 secondObj; 
    string data; 
    string token; 
    in>>data; 
    in.ignore(); 
    token = GetToken(data, ' ', someint); //This is designed to take a part of data 
    stringstream ss(token); // I copied token into ss 
    ss >> secondObj; // This is where I run into problems. 
} 
template<class T> 
ostream& operator <<(ostream out, const Object1<T>& output){ 
    Object2<T>* ptr; 
    while(GetNextPtr(ptr) != NULL){ 
     cout<<ptr; 
     ptr = GetNextPtr(ptr); //Assume that I have this function in Object2.h 
    } 
} 

的Object2.h文件類似於Object1.h情況除外:

template<class T> 
class Object2{ 
public: 
//similar istream and ostream funcions of Object1 
//a GetNextPtr function 
private: 
    T data; 
    Object2<T>* next; 
}; 
template<class T> 
istream& operator >>(istream& in, Object2<T>& input){ 
     in>>data; //data is the private member variable in Object2. 
       //it is of a templated class type. 
} 

回答

0

以下編譯罰款:

#include <string> 
#include <sstream> 
#include <iostream> 

using namespace std; 

struct X{}; 

struct Y{}; 

istream& operator>>(istream&, X&) {} 

istream& operator>>(istream&, Y&) 
{ 
    stringstream ss("foo"); 

    X x; 
    ss >> x; 
} 

int main() 
{ 
    Y y; 
    cin >> y; 
} 

你的問題一定是在別處

你可以發佈一個完整的最小的獨立程序演示問題?或者只是你的聲明和定義的功能istream& operator >>(istream& in, Object2& input)?它是否在翻譯單元中的Object1版本之前聲明?

+0

@布魯斯:它不夠。通過將所使用的零件提取到一個小型測試程序中來分解問題。如果這項工作繼續添加東西,直到它停止工作。如果測試程序不起作用,請將其發佈到此處。 – 2013-04-20 01:07:07

+0

我發佈了一些更多信息。我正在製作一個模板鏈接列表。我不知道錯誤是否發生,因爲這些類是模板化的。 – Bruce 2013-04-20 01:29:30