2017-02-24 127 views
-2

標題說全部不能使用`cout`。我在互聯網上的每個人都說超載運營商< <,但我仍然爲一個無效的運營商得到了這個愚蠢的錯誤。我做錯了什麼?這裏是我的代碼:即使我超載`運營商<<`

#include <iostream> 
#include <cstdio> 

using namespace std; 

class Calc { 
private: 
    union _Print_Datatypes { 
     int I; 
     double D; 
     string S; 
     char C; 
    }; 
public: 
    int i; 
    void Sum(long double _a, long double _b) { 
     return _a + _b; 

    } 
    void Sub(long double _a, long double _b) { 
     return _a - _b; 

    } 
    void Div(long double _a, long double _b) { 
     return _a/_b; 

    } 
    void Mult(long double _a, long double _b) { 
     return _a * _b; 

    } 
}; 


std::ostream &operator<<(std::ostream &os, Calc const &m) { 
    return os << m.i; 
} 

int main() { 

    Calc _calc; 
    cout << _calc.Sum(2,2); 
} 
+1

你得到了什麼確切的錯誤? – NathanOliver

+1

總和成員函數的返回類型是什麼...? ;) –

+0

... \ main.cpp | 42 |錯誤:'operator <<'不匹配(操作數類型是'std :: ostream {aka std :: basic_ostream }'和'void')| –

回答

2
cout << _calc.Sum(2,2); 

的返回類型從Sum()方法是void。顯然,operator<<void上不起作用。

您需要更改您的Sum()等,返回Calc &,並讓他們返回*this

1

您的代碼甚至不無<<編譯:

main.cpp:17:9: error: void function 'Sum' should not return a value [-Wreturn-type] 
     return _a + _b; 
     ^ ~~~~~~~ 

你的函數聲明爲返回void

+0

將它們全部更改爲int。謝啦! –

+0

@ UlisseBenedettiUlisse54:爲什麼返回int如果你的參數長雙重? – stefaanv

+0

順便說一下,當你執行'Calc c; c.i = 5; std :: cout << c;',而不是當你做'Calc c; std :: cout << c.Sum(1.0,2.0);'如果它返回像int這樣的原始類型。 – stefaanv