C++友元函数问题,类的成员函数无法访问私有成员

2025-03-14 00:25:53
推荐回答(1个)
回答1:

 改成下面的代码 就能执行了。。vc6编译通过。。

#include 
using namespace std;
class X; //这里要前导声明
class Y
{
public:
 bool ifelse(X& temp);  
};

class X
{
public:
friend bool Y::ifelse(X&);
private:
int a;
int b;
};
 
bool Y::ifelse(X& temp)  
{
 return temp.a > temp.b ? true : false;
}
 
int main()
{  
 X x;
 Y y;
 if (y.ifelse(x)) cout<<"it is true"< else cout<<"it is false!"< return 0;
}