小编Arv*_*tel的帖子

使用友元函数,我们可以覆盖该类的私有成员吗?

在给定的c ++代码中,类DEF的私有成员在构造函数中初始化,并再次在友元函数内部进行初始化.所以重新定义会覆盖私有变量,否则构造函数给出的值会持续存在?

#include<iostream>

//class DEF;

class ABC{
        public:
                 int fun(class DEF);
};

class DEF{
        private:
                int a,b,c;

        public:
        DEF():a(1),b(12),c(2){}
        friend  int ABC::fun(class DEF);/*Using friend function to access the private member of other class.*/
        void fun_2();
};

void DEF::fun_2(){
        cout<<"a : "<<&a<<' '<<"b : "<<&b<<' '<<"c: "<<&c<<endl;
        cout<<"a : "<<a<<' '<<"b : "<<b<<' '<<"c: "<<c<<endl;
}

int ABC::fun(class DEF A){
        A.a = 10;
        A.b = 20;
        A.c = 30;

        int data = A.a + A.b + A.c;
        cout<<"a : "<<&(A.a)<<' '<<"b …
Run Code Online (Sandbox Code Playgroud)

c++ friend-function

5
推荐指数
1
解决办法
303
查看次数

标签 统计

c++ ×1

friend-function ×1