这两天一直被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>。