2014-10-31 67 views
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 
} 
+1

您需要公開操作員。 – Barry 2014-10-31 01:58:11

+2

@Barry'friend'聲明可以發生在類聲明中的任何地方。在這種情況下,「private」/「public」並不重要。 – 2014-10-31 01:59:52

+0

真的嗎?涼。不知道(顯然:)) – Barry 2014-10-31 02:02:44

回答

4

你的錯誤是在這裏

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

這不符合您定義的(正確的)簽名

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

當然,草率的複製/粘貼錯誤。修復它,謝謝。 – Sabien 2014-10-31 02:05:22

相關問題