c++ - C++ 中的运算符重载 <<

标签 c++ io operator-overloading

我写了这个简单的程序来练习重载。

这是我的代码:

#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/

相关文章:

C++ STM32用户定义类构造函数问题

c++ - 从 const 函数返回非常量属性引用

file - Golang,倒带文件指针的正确方法

multithreading - Clojure 消息处理/异步、多线程

c++ - 是否可以对全局运算符 `new` 和 `delete` 执行回调?

c++ - 使用重载运算符 () C++ 时出错

c++ - 计算正方形的方向并显示具有相同方向的对象

java - 使用FileOutputStream写入的数据在重新启动程序后消失

operator-overloading - 覆盖/重载 + 运算符以对常见的 lisp 向量进行操作

C++ 删除 vector 中的元素