gpt4 book ai didi

c++ - 重载后无法调用 std::minus - 运算符

转载 作者:行者123 更新时间:2023-11-30 03:28:12 25 4
gpt4 key购买 nike

我的以下 C++ 代码片段出现编译错误。

struct Power{
int power;
int age;
int operator-(const Power& p1)
{
return this->power - p1.power;
}
};


int main() {
Power p1;
p1.power = 1;
p1.age = 25;
Power p2;
p2.power = 2;
p2.age = 26;
std::cout<<std::minus<Power>()(p1, p2)<<std::endl;
}

使用 C++11 构建。无法 build 。错误信息是:

 error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Power’)
std::cout<<std::minus<Power>()(p1, p2)<<std::endl;
^
In file included from /usr/include/c++/5/iostream:39:0,
from rvaluereference.cpp:1:
/usr/include/c++/5/ostream:628:5: note: candidate: std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Power] <near match>
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^
/usr/include/c++/5/ostream:628:5: note: conversion of argument 1 would be ill-formed:
rvaluereference.cpp:60:39: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
.....

最佳答案

std::minus has a single template parameter定义输入和输出的类型;它不处理类型切换 AFAICT。你的operator-需要 Power ,并返回 int ,但是 std::minus<Power>必须拿走并返回 Power .投诉是因为std::minus<Power>返回 Power , 和 ostream operator<< 没有过载接受 Power .

如评论中所述,如果您可以使用 C++14 , std::minus<void> accepts mismatched arguments and deduces the return type , 所以如果你可以使用 C++14 ,这是另一种选择。

关于c++ - 重载后无法调用 std::minus - 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782290/

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