C++的重载流输出运算符

简介: // 下列代码输出什么? #include <iostream> #include <string> // typedef basic_ostream<char> ostream; class A { private:     int m1,m2; public:     A(int a, i.
// 下列代码输出什么?
#include <iostream>
#include <string>

// typedef basic_ostream<char> ostream;
class A
{
private:
    int m1,m2;

public:
    A(int a, int b) {
        m1=a;m2=b;
    }

    operator std::string() const { return "str"; }
    operator int() const { return 2018; }
};

int main()
{
    A a(1,2);
    std::cout << a;
    return 0;
};


答案是2018,
因为类basic_ostream有成员函数operator<<(int),
而没有成员函数operator<<(const std::string&),
优先调用同名的成员函数,故输出2018,相关源代码如下:

// 名字空间std中的全局函数
/usr/include/c++/4.8.2/bits/basic_string.h:
template<typename _CharT, typename _Traits, typename _Alloc>
inline basic_ostream<_CharT, _Traits>&
operator <<(basic_ostream<_CharT, _Traits>& __os,
            const basic_string<_CharT, _Traits, _Alloc>& __str)
{
    return __ostream_insert(__os, __str.data(), __str.size());
}

// 类basic_ostream的成员函数
//  std::cout为名字空间std中的类basic_ostream的一个实例
ostream:
__ostream_type& basic_ostream::operator<<(int __n);

// 下列代码有什么问题,如何修改?
#include <iostream>
#include <string>

class A
{
public:
    int m1,m2;

public:
    A(int a, int b) {
        m1=a;m2=b;
    }

    std::ostream& operator <<(std::ostream& os) {
        os << m1 << m2; return os;
    }
};

int main()
{
    A a(1,2);
    std::cout << a;
    return 0;
};

类basic_ostream没有成员函数“operator <<(const A&)”,
也不存在全局的:
operator <<(const basic_ostream&, const A&)
而只有左操作数是自己时才会调用成员重载操作符,
都不符合,所以语法错误。

有两种修改方式:
1) 将“std::cout << a”改成“a.operator <<(std::cout)”,
2) 或定义全局的:
std::ostream& operator<<(std::ostream& os, const A& a) {
    os << a.m1 << a.m2; return os;
}
相关文章
|
13天前
|
C++
C++程序中的赋值运算符
C++程序中的赋值运算符
23 2
|
6天前
|
C++
c++运算符
c++运算符
20 2
|
6天前
|
程序员 编译器 C++
c++重载运算符和重载函数
c++重载运算符和重载函数
12 1
|
8天前
|
存储 安全 程序员
C++中的四种类型转换运算符
reinterpret_cast` 则是非常危险的类型转换,仅用于二进制级别的解释,不检查安全性。`dynamic_cast` 用于类的继承层次间转换,向上转型总是安全的,向下转型时会借助 RTTI 进行安全性检查。只有当转换路径在继承链内时,转换才会成功。
9 1
|
9天前
|
程序员 C++
C++中的运算符:深入理解与应用
C++中的运算符:深入理解与应用
|
10天前
|
C++
C++ 重载 数组对象输入输出流的实现!!!
C++ 重载 数组对象输入输出流的实现!!!
|
18天前
|
C++ 编译器
|
18天前
|
编译器 C++
【C++】类与对象(运算符重载、const成员、取地址重载)
【C++】类与对象(运算符重载、const成员、取地址重载)
20 2
|
18天前
|
编译器 C语言 C++
【C++】基础知识讲解(命名空间、缺省参数、重载、输入输出)
【C++】基础知识讲解(命名空间、缺省参数、重载、输入输出)
13 1
【C++】基础知识讲解(命名空间、缺省参数、重载、输入输出)
|
18天前
|
C++
【C++小小知识点】重载、覆盖(重写)、隐藏(重定义)的对比【详解】(23)
【C++小小知识点】重载、覆盖(重写)、隐藏(重定义)的对比【详解】(23)