gpt4 book ai didi

c++ - 类的私有(private)成员 - 在此上下文中

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:05 25 4
gpt4 key购买 nike

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

看看这个:

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

最佳答案

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

不一样

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

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

关于c++ - 类的私有(private)成员 - 在此上下文中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26012621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com