C ++ istream运算符重载 - 即使声明为朋友也无法访问数据成员

时间:2014-10-31 01:56:18

标签: c++ operator-overloading istream

我有一个类Complex,我正在尝试重载istream运算符>>允许用户以“(a,b)”的形式输入复数。下面是我的头文件和我的实现。现在,我收到一个错误,说我的重载>>函数无法访问真实或虚构的数据成员,因为它们是不可访问的,即使我在类头文件中声明它们是朋友。谁能解释一下我没看到的东西?

标题文件:

// Complex class definition.
#ifndef COMPLEX_H
#define COMPLEX_H

class Complex
{
friend std::ostream &operator<<(std::ostream &, const Complex &);
friend std::istream &operator>>(std::istream &, const Complex &);
public:
   explicit Complex( double = 0.0, double = 0.0 ); // constructor
   Complex operator+( const Complex & ) const; // addition
   Complex operator-( const Complex & ) const; // subtraction
   //Complex operator*(const Complex &); // function not implemented yet
private:
   double real; // real part
   double imaginary; // imaginary part
}; // end class Complex

#endif

实施档案:

// Complex class member-function definitions.
#include <iostream>
#include <iomanip>
#include "Complex.h" // Complex class definition
using namespace std;

// Constructor
Complex::Complex( double realPart, double imaginaryPart ) 
   : real( realPart ),
   imaginary( imaginaryPart ) 
{ 
   // empty body
} // end Complex constructor

// addition operator
Complex Complex::operator+( const Complex &operand2 ) const
{
   return Complex( real + operand2.real, 
      imaginary + operand2.imaginary );
} // end function operator+

// subtraction operator
Complex Complex::operator-( const Complex &operand2 ) const
{
   return Complex( real - operand2.real, 
      imaginary - operand2.imaginary );
} // end function operator-

// display a Complex object in the form: (a, b)
ostream &operator<<(ostream &out, const Complex &operand2)
{
   out << "(" << operand2.real << ", " << operand2.imaginary << ")";

   return out; // enable cascading output
}

// change the imaginary and real parts
istream &operator>>(istream &in, Complex &operand2)
{
   in.ignore(); // skips '('
   in >> setw(1) >> operand2.real; // get real part of the number
   in.ignore(2); //ignore the , and space
   in >> setw(1) >> operand2.imaginary;
   in.ignore(); // skip ')'
   return in; // enable cascading input
}

1 个答案:

答案 0 :(得分:4)

您的错误在这里

 friend std::istream &operator>>(std::istream &, const Complex &);
                                              // ^^^^^

这与您定义的(正确)签名不匹配

 istream &operator>>(istream &in, Complex &operand2)