【问题标题】:Private members of class - within this context类的私有成员 - 在这种情况下
【发布时间】:2014-11-18 16:39:35
【问题描述】:

我收到奇怪的通知,说我正在使用类的私有成员 - 这是完全有效的,但我认为我可以这样做,因为我确实说过我使用的方法是一种友好的方法。

看看这个:

#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 以获得私有值吗?

【问题讨论】:

    标签: c++


    【解决方案1】:
    istream& operator>>(istream &, const complex &);
    

    不一样

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

    找出差异作为练习留给读者。

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多