2017-10-17 53 views
0

我的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; 
} 

build with 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>&&’ 
..... 
+0

你讓這聽起來像它使用重載運算符之前的工作。直接輸出'p1 - p2'也不起作用。這與'std :: minus'無關。 – chris

+0

我確定p1 - p2與C++一起工作11 –

+0

哦,那是我的不好。我沒有看到它通常會返回'int'而不是'Power',就像減法一樣。 – chris

回答

3

std::minus has a single template parameter限定的兩個輸入和輸出的類型;它不處理類型切換AFAICT。您的operator-需要Power,並且返回int,但std::minus<Power>必須帶並返回Power。投訴是因爲std::minus<Power>返回Power,並且ostream沒有接受Poweroperator<<超載。

如評論中所述,如果您可以使用C++14,std::minus<void> accepts mismatched arguments and deduces the return type,那麼如果您可以使用C++14,那是另一種選擇。

+0

謝謝。並且在我將它改爲std :: cout <<(std :: minus ()(p1,p2))後。age << std :: endl;並重新定義運營商 - 如Power運營商 - (const Power&p1) \t { \t \t return p1; \t}它仍然不起作用... –

+0

@WubinOuyang:「不起作用」不是特別有用; *如何在變更後失敗? – ShadowRanger

+0

/usr/include/c++/5/bits/stl_function.h:182:20:錯誤:'operator-'不匹配(操作數類型是'const Power'和'const Power') {return __x - __y; } –

-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;

+0

OP明確地要使用'std :: minus'。說「不要使用std :: minus」「是一種旁白。除此之外,雖然非成員函數對於'operator-'更爲正確(因爲它是非變異的),所以如果std :: minus成員遵循所需的模式(函數是'const',參數是與其定義的類相同類型的'const'引用,並且結果是相同類型的非''contst'值)。 – ShadowRanger

+0

@ShadowRanger是的,但是這裏'operator-'沒有返回'Power',是嗎?因此'std :: minus'對於此用法無效。 – N00byEdge