[英]C++ operator unexpected error
I' m trying to define an operator for a class like this: 我正在尝试为此类定义一个运算符:
file.h 文件
bool operator<<(XMLPair *p2);
file.cpp file.cpp
bool XMLPair::operator<<(XMLPair *p2)
{
....
}
When I try to use it in the main program like this 当我尝试在这样的主程序中使用它时
XMLPair *p1, *p2 ;
...
p1<<p2
it says 它说
error: invalid operands of types ‘XMLPair*’ and ‘XMLPair*’ to binary ‘operator<<’
Any idea? 任何想法?
p1
is a pointer; p1
是一个指针; the left hand argument of a member operator has to be an object. 成员运算符的左手参数必须是一个对象。 So you need:
因此,您需要:
(*p1) << p2;
Although it would be more idiomatic for the right-hand argument to be a reference, and only to use pointers when you really need to: 尽管将右手参数用作引用会更加惯用,并且仅在确实需要使用指针时才使用:
// Remove `const` as necessary, if the operator needs to modify either operand
bool operator<<(XMLPair const & p2) const;
XMLPair p1, p2;
p1 << p2;
左侧必须是一个对象,而不是指针,请尝试:
(*p1) << p2;
You declared pointer to p1, and you call the operator on pointer. 您声明了指向p1的指针,并在指针上调用了运算符。 Try to invoke operator on (*p1), instead of p1.
尝试在(* p1)而不是p1上调用运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.