다음 C++ 코드 단편에 대한 컴파일 오류가 발생합니다.오버로드 후 std :: minus를 호출 할 수 없습니다 - 연산자
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>&&’
.....
을 수행 할 수 있습니다 클래스의 외부 연산자를 선언합니다. 'p1 - p2 '를 출력해도 직접 동작하지 않습니다. 이것은'std :: minus'와는 관련이 없습니다. – chris
확실히 p1 - p2는 C++와 작동합니다. 11 –
오, 그게 나쁘군요. 나는 그것이 빼기와 같이'Power' 대신'int'를 리턴한다는 것을 보지 못했습니다. – chris