如题,同样是私有函数做友元,两段代码一个报错一个不报错:
这段不报错
#include <iostream>
using namespace std;
// forward declare
class A;
class B;
// class declare
class B
{
public:
void saysomething(A& a);
private:
void saybye(A& a);
friend class A;
};
class A
{
friend void B::saybye(A&);
private:
void sayhi();
};
// method declare
void A::sayhi()
{
cout << "hi" << endl;
}
void B::saysomething(A& a)
{
saybye(a);
}
void B::saybye(A& a)
{
a.sayhi();
cout << "bye" << endl;
}
int main(void)
{
A a;
B b;
b.saysomething(a);
return 0;
}
这段报错:
1.cpp: In function ‘int main()’:
1.cpp:24:5: error: ‘int Scale::getWeight(IceCream)’ is private
int Scale::getWeight(IceCream obj)
^
1.cpp:33:75: error: within this context
cout << "DairyQueen's totalWeight is: " << eScale.getWeight(dairyQueen) << endl;
^
代码:
#include <iostream>
using namespace std;
class IceCream;
class Scale
{
private:
int getWeight(IceCream obj);
friend class IceCream;
};
class IceCream
{
// 其他类的成员函数声明为友元
friend int Scale::getWeight(IceCream obj);
private:
int totalWeight = 10;
};
// 类Scale的成员函数
int Scale::getWeight(IceCream obj)
{
return obj.totalWeight;
}
int main()
{
IceCream dairyQueen;
Scale eScale;
cout << "DairyQueen's totalWeight is: " << eScale.getWeight(dairyQueen) << endl;
return 0;
}
请问这个哪里有问题吗?