班级的私人成员 - 在此背景下

时间:2014-09-24 08:55:59

标签: c++

我得到奇怪的通知,我正在使用私有的类成员 - 这是完全有效的,但我虽然我被允许这样做,因为我确实说我正在使用的方法是友好的。

看看这个:

#include <iostream> 

using namespace std; 


class complex {

private:
   double Re, Im;  

public:

  complex(): Re(0.0), Im(0.0){}
  complex(double Re, double Im): Re(Re), Im(Im){}
  double getRe() const { return Re; }
  double getIm() const { return Im; }
  friend complex operator+(const complex&, const complex&); 
  friend ostream& operator<<(ostream&, const complex&); 
  friend istream& operator>>(istream &, const complex &); // FRIENDLY FUNCTION
};


complex operator+(const complex& a, const complex& b) {
   double r, i;
   r = a.getRe()+ b.getRe();
   i = a.getIm() + b.getIm();
   return complex(r, i); 
}

ostream& operator<<(ostream& out, const complex &a) {
  out << "(" << a.getRe() << ", " << a.getIm() << ")" << endl;
  return out;
}

istream &operator>>(istream &in,  complex &c)    
{
    cout<<"enter real part:\n";
    in>>c.Re; // ** WITHIN THIS CONTEXT ERROR **
    cout<<"enter imag part: \n";
    in>>c.Im; // ** WITHIN THIS CONTEXT ERROR ** 
    return in;
}

int main(void) {
 complex a, b,c; 

 cin >> a;
 cin >> b; 
 c = a+b;

cout << c; 

}

我是否应该在类中声明某种setFunction以获取私有值?

1 个答案:

答案 0 :(得分:5)

istream& operator>>(istream &, const complex &);

不同
istream &operator>>(istream &in, complex &c);

将作为锻炼的差异发现给读者。