gpt4 book ai didi

C++ 运算符意外错误

转载 作者:行者123 更新时间:2023-11-27 23:26:27 25 4
gpt4 key购买 nike

我正在尝试为这样的类定义一个运算符:

文件.h

bool operator<<(XMLPair *p2);

文件.cpp

bool XMLPair::operator<<(XMLPair *p2)
{
....
}

当我尝试像这样在主程序中使用它时

XMLPair *p1, *p2 ;
...
p1<<p2

它说

error: invalid operands of types ‘XMLPair*’ and ‘XMLPair*’ to binary ‘operator<<’

有什么想法吗?

最佳答案

p1 是一个指针;成员运算符的左手参数必须是一个对象。所以你需要:

(*p1) << p2;

虽然将右边的参数作为引用会更加惯用,并且仅在您确实需要时才使用指针:

// Remove `const` as necessary, if the operator needs to modify either operand
bool operator<<(XMLPair const & p2) const;

XMLPair p1, p2;
p1 << p2;

关于C++ 运算符意外错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com