[英]C++ operator overloading error: no match for 'operator>>' in 'is >> “(”'
I'm trying to learn operator overloading and I got an error on my first attempt. 我正在尝试学习运算符重载,并且第一次尝试时遇到错误。
template<typename T>
class Pair
{
public:
T x; T y;
Pair(T x, T y): x(x), y(y){};
~Pair(){};
/* data */
};
template<typename T>
ostream& operator<<(ostream &os, const Pair<T> &p)
{
return os<<"("<<p.x<<", "<<p.y<<")";
}
template<typename T>
istream& operator>>(istream &is, Pair<T> &p)
{
return is>>"(">>p.x>>", ">>p.y>>")";
}
I want to be able to do the following: 我希望能够执行以下操作:
Pair<int> p;
cin>>p;
cout<<p;
And giving input for Pair
object means being able to give (1, 2)
as input which after cin
, produces a Pair<int>
. 并且为Pair
对象提供输入意味着可以提供(1, 2)
作为输入,在cin
之后,产生Pair<int>
。
I get a compile time error at is>>"("
. What is the way to correct this? 我在is>>"("
处收到编译时错误。如何解决此问题?
return is>>"(">>p.x>>", ">>p.y>>")";
is nonsense: you are trying to move the information of the stream 'is' into the constant string ")". 是胡说八道:您正在尝试将流“ is”的信息移到常量字符串“)”中。 I think what you want is this: 我认为您想要的是:
template<typename T>
istream& operator>>(istream &is, Pair<T> &p)
{
is.seekg(1, std::ios::cur); // skip 1 char, "("
is >> p.x;
is.seekg(2, std::ios::cur); // skip 2 chars, ", "
is >> p.y;
is.seekg(1, std::ios::cur); // skip 1 char, ")"
}
You are trying to read into string literals "("
and ")"
. 您正在尝试将字符串文字"("
和")"
读入。 You cannot do that. 你不能这样做。
Try this: 尝试这个:
template<typename T>
istream& operator>>(istream &is, Pair<T> &p)
{
return is >> p.x>> p.y;
}
As others have pointed out, you're trying to read into literals in the extractor. 正如其他人指出的那样,您正在尝试在提取器中读取文字。 I'd suggest fixing this by reading a char
first and comparing it with '('
. You signal an error if that fails, otherwise extract T
and repeat the process. 我建议先读取一个char
并将其与'('
进行比较,以解决此问题。如果失败,您会发出错误信号,否则请提取T
并重复该过程。
In code: 在代码中:
template <typename T>
istream& operator>> (istream &is, Pair<T> &p)
{
char c;
if (!(is >> c)) return is;
if (c != '(') {
is.setstate(is.failbit);
return is;
}
if (!(is >> p.x >> c)) return is;
if (c != ',') {
is.setstate(is.failbit);
return is;
}
if (!(is >> p.x >> c)) return is;
if (c != ')') {
is.setstate(is.failbit);
}
return is;
}
您不必在输入运算符重载中读取“(”字符串文字,只需读取px和py。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.