Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何执行friend类?_C++_Class_Friend - Fatal编程技术网

C++ 如何执行friend类?

C++ 如何执行friend类?,c++,class,friend,C++,Class,Friend,我试图实现friend类,为另一个类的成员提供成员的值 我尝试将类的对象设为Friend,并将其定义为尝试的参数,然后将&Friend::fri替换为对象.fri(),但它也未编译 class Friend { public: int val = 0; int fri() { val = 456; return val; } friend class Partner; }; class Partner { pu

我试图实现friend类,为另一个类的成员提供成员的值

我尝试将
类的对象设为Friend
,并将其定义为
尝试
的参数,然后将
&Friend::fri
替换为
对象.fri()
,但它也未编译

 class Friend {
  public:
    int val = 0;
int fri() {
    val = 456;
    return val;         
          }
friend class Partner;
 };

 class Partner {    
  public:
//(corrected) Friend Object;
int Attempt() {
    std::cout << "The value from the friend class: " << 
     &Friend::fri /*(corrected) Object.fri()*/<<"\n"; // '&' was requred by compiler to make pointer to 
                        //the member
    return 0;
      }
 };
班友{
公众:
int-val=0;
int fri(){
val=456;
返回val;
}
朋友级伙伴;
};
类伙伴{
公众:
//(更正)友人对象;
int尝试(){

std::coutfriend关键字只允许非成员函数访问另一个类的私有/受保护成员。除非您的方法是静态的,或者涉及继承,否则您仍然需要一个对象来调用该方法。例如:

Friend f;
int Attempt(){
    std::cout << "The value from the friend class: " << f.fri();
}
Friend;
int尝试(){

std::cout谢谢,它确实返回了所需的值。@Konstantin很高兴它有帮助。如果它解决了您的问题,请随意标记它为正确,以防将来有人遇到此问题:)上次我更正了代码,但在有人写了不这样做的代码后,现在我真的不知道在问题解决后该怎么办)Gues(如果我在代码中添加注释,这将是最佳解决方案)