我写了这个简单的程序来练习重载。
这是我的代码:
#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
最佳答案
参数和返回自 operator<<
是非常量。它还需要是非成员-您已经为 me << cout
编写了重载, 不是 cout << me
.此外,以两个下划线开头的标识符是为实现保留的,使用它们是未定义的行为。
关于c++ - C++ 中的运算符重载 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11218790/