我写了这个简单的程序来练习重载。
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
class sex_t
{
private:
char __sex__;
public:
sex_t(char sex_v = 'M'):__sex__(sex_v)
{
if (sex_v != 'M' && sex_v != 'F')
{
cerr << "Sex type error!" << sex_v << endl;
__sex__ = 'M';
}
}
const ostream& operator << (const ostream& stream)
{
if (__sex__ == 'M')
cout << "Male";
else
cout << "Female";
return stream;
}
};
int main(int argc, char *argv[])
{
sex_t me('M');
cout << me << endl;
return 0;
}
当我编译它时,它会打印很多错误消息:
错误消息一团糟。
我很难找到有用的信息。
sex.cpp: 在函数‘int main(int, char**)’中:
sex.cpp:32:10: 错误: ‘operator<<’在‘std::cout << me’中没有匹配
sex.cpp:32:10: 附注: 备选是:
/usr/include/c++/4.6/ostream:110:7: 附注: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostre