2017-02-24 129 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