VC6.0中有关输出运算符<<的重载问题(备忘)

这两天一直被C++中重载输出运算符的问题困扰,查阅多方资料无果。今天在MSDN论坛翻了很久,终于找到解答,此文仅用于备忘,以便日后查阅。以下为测试小程序:

// Complex.h: interface for the Complex class. // // #include <iostream.h> #if !defined(AFX_COMPLEX_H__77D2DEF8_D9C4_4935_98AC_E83A86B105DA__INCLUDED_) #define AFX_COMPLEX_H__77D2DEF8_D9C4_4935_98AC_E83A86B105DA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class Complex { public: Complex(double real, double img); Complex(); virtual ~Complex(); friend ostream& operator <<(ostream &out, const Complex &obj); private: double m_real; double m_img; }; #endif // !defined(AFX_COMPLEX_H__77D2DEF8_D9C4_4935_98AC_E83A86B105DA__INCLUDED_)

// Complex.cpp: implementation of the Complex class. // // #include "Complex.h" // // Construction/Destruction // Complex::Complex():m_real(0.0), m_img(0.0) { } Complex::~Complex() { } Complex::Complex(double real, double img) { m_real = real; m_img = img; } ostream& operator <<(ostream &out, const Complex &obj) { out << obj.m_real << "+" << obj.m_img << "i"; return out; }

起初,在Complex.h文件中,使用:

#include<iostream>

using namespace std;

结果编译时出现错误,提示<<不能访问Complex的私有成员。

后改正为#include<iostream.h>,编译通过,且运行正常。

分析:

vc60下的<iostream> 不支持友元<<的重载方式。所以在6.0下若想以友元方式重载<<(输出运算符)的话,应该包含头文件<iostream.h>而非<iostream>。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值