调用std :: minus在重载之后无法工作 - 运算符

时间:2017-10-17 04:05:31

标签: c++ std

我的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构建。无法建造。 错误信息是:

 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>&&’
.....

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:-1)

虽然std::minus只能T operator-(const T &lhs, const T &rhs),但您的运营商没有相同的限制。在类之外声明运算符:

int operator-(const Power &lhs, const Power &rhs) {
    return lhs.power - rhs.power;
}

现在你可以std::cout << p1 - p2 << std::endl;