qq_45735316
qq_45735316
采纳率80.7%
2020-04-03 10:19

已经声明了友元函数为什么还是不能访问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条回答

  • qq_39554698 小学狗喵喵叫 1年前

    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;
    }
    
    点赞 1 评论 复制链接分享