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.
}
@布鲁斯:它不够。通过将所使用的零件提取到一个小型测试程序中来分解问题。如果这项工作继续添加东西,直到它停止工作。如果测试程序不起作用,请将其发布到此处。 – 2013-04-20 01:07:07
我发布了一些更多信息。我正在制作一个模板链接列表。我不知道错误是否发生,因为这些类是模板化的。 – Bruce 2013-04-20 01:29:30