0
我有一个类复杂,我想重载istream运算符>>,以允许用户输入一个复杂的数字形式“(a,b )”。以下是我的头文件和我的实现。现在,我收到一个错误,说我的重载的>>函数不能访问真实或想象的数据成员,因为它们是不可访问的,即使我在类头文件中将它们声明为朋友。任何人都可以解释我没有看到什么吗?C++ istream运算符重载 - 不能访问数据成员,即使声明的朋友
头文件
// 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
}
您需要公开操作员。 – Barry 2014-10-31 01:58:11
@Barry'friend'声明可以发生在类声明中的任何地方。在这种情况下,“private”/“public”并不重要。 – 2014-10-31 01:59:52
真的吗?凉。不知道(显然:)) – Barry 2014-10-31 02:02:44