qq_45735316 2020-04-03 10:19 采纳率: 94.1%
浏览 584
已采纳

已经声明了友元函数为什么还是不能访问x的私有数据?还有这个头文件的引用方式是对的吗?

图片说明

#include <iostream>
#include "Classfile.h"
using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//C++ P186 5-13

int main(int argc, char** argv) {
    X x;
    Y y;
    Z z;
    x(5);
    y.g(x);
    z.f(x);
    return 0;
}

class X{
    public:
        friend void g(X x);
        friend class Z;
        friend void h(X x);
        X(int i=0):i(i){}
    private:
        int i;
};
class Y{
    public:
        void g(X x);
    private:
};
void Y::g(X x){
    x.i=x.i+1;
    cout<<"i="<<x.i<endl;
}
class Z{
    public:
         void f(X x);
    private:
        X x; 
};
void Z::f(X x)
{
    x.i=x.i+5;
    cout<<"i="<<x.i<endl;
}
void h(X x)
{
    x.i=x.i+10;
    cout<<"i="<<x.i<endl;   
}
  • 写回答

1条回答 默认 最新

  • 小学狗喵喵叫 2020-04-03 10:43
    关注

    Classfile.h

    class X {
    public:
        friend class Y;
        friend class Z;
        friend void h(X x);
        X(int i = 0) :i(i) {}
    private:
        int i;
    };
    class Y{
        public:
            void g(X x);
        private:
    };
    
    class Z{
        public:
             void f(X x);
        private:
            X x; 
    };
    
    void h(X x);
    

    Classfile.cpp

    #include <iostream>
    #include "Classfile.h"
    using namespace std; 
    
    void Y::g(X x){
        x.i=x.i+1;
        cout<<"i="<<x.i<<endl;
    }
    
    void Z::f(X x)
    {
        x.i=x.i+5;
        cout<<"i="<<x.i<<endl;
    }
    void h(X x)
    {
        x.i=x.i+10;
        cout<<"i="<<x.i<<endl;   
    }
    
    

    P186 5-13.cpp

    #include <iostream>
    #include "Classfile.h"
    using namespace std; 
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    //C++ P186 5-13
    
    int main(int argc, char** argv) {
        X x(5);
        Y y;
        Z z;
        y.g(x);
        z.f(x);
        h(x);
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?