Bru*_*uce 5 c++ overloading operators stringstream extraction
我试图将字符串流传递到具有>>声明和定义的重载提取运算符的对象(类)中。例如,object1中重载提取运算符的声明为
friend istream& operator >>(istream& in, Object1& input);
Run Code Online (Sandbox Code Playgroud)
在object2中,我的声明几乎相同
friend istream& operator >>(istream& in, Object2& input);
Run Code Online (Sandbox Code Playgroud)
在object1提取功能期间,函数。获取一行,将其转换为字符串流,并尝试使用Object2的extract(>>)运算符。
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.
}
Run Code Online (Sandbox Code Playgroud)
我得到了错误No match for operator >>。这是因为我需要将stringstream转换为istream吗?如果是这样,我该怎么做?
最小程序如下所示:在main.cpp中:
#include "Object1.h"
#include "Object2.h"
#include "dataClass.h"
using namespace std;
int main(){
Object1<dataClass> firstObj;
cin>>firstObj;
cout<<firstObj<<endl;
}
Run Code Online (Sandbox Code Playgroud)
在Object1.h中:
#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
}
}
Run Code Online (Sandbox Code Playgroud)
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.
}
Run Code Online (Sandbox Code Playgroud)
以下编译良好:
#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;
}
Run Code Online (Sandbox Code Playgroud)
你的问题一定在其他地方
您可以发布一个完整的最小独立程序来演示该问题吗?或者只是你的函数的声明和定义istream& operator >>(istream& in, Object2& input)?它是否在翻译单元中的 Object1 版本之前声明?