【发布时间】:2015-11-07 22:13:07
【问题描述】:
我有以下课程:
class PhoneCall{
private:
string number;
public:
/*some code here */
};
现在,我已经声明了一个函数(不是 friend 到 PhoneCall),它执行一些特定操作并返回一个 PhoneCall 对象
PhoneCall callOperation()
另一个将 PhoneCall 对象作为参数
void userCall(PhoneCall obj)
我希望它不会工作,除非它被明确声明为该类的朋友。
即使这些函数不是 PhoneCall 类的朋友,为什么以及如何工作?
一个类的友元函数是在该类的范围之外定义的,但是 它有权访问所有私有和受保护的成员 班级 http://www.tutorialspoint.com/cplusplus/cpp_friend_functions.htm
【问题讨论】:
-
您认为:
userCall()需要 PhoneCall 的哪个私有或受保护成员? -
如果你用
std::string类型声明那些函数而不是PhoneCall,你需要这些函数与std::string成为朋友吗? -
A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class。它并不是说非友元函数不能返回或接受该类的对象作为参数。 -
在原型中声明,
userCall()通过 setter @fukanchik 访问成员string number -
@AbrarShariarGalib 哦,真的吗?这个原型的哪一部分声明了这一点?