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

时间:2016-03-25 07:52:16

标签: c++ friend-function

在给定的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 : "<<&(A.b)<<' '<<"c: "<<&(A.c)<<endl;
        cout<<"a : "<<A.a<<' '<<"b : "<<A.b<<' '<<"c: "<<A.c<<endl;
        return data;
}

int main(){
        cout<<"Inside main function"<<endl;
        ABC obj_1;
        DEF obj_2;
        obj_2.fun_2();
        int sum = obj_1.fun(obj_2);
        cout<<"sum : "<<sum<<endl;
        obj_2.fun_2();

}

1 个答案:

答案 0 :(得分:2)

在下面一行:

int ABC::fun(class DEF A)

您正在按值传递参数,因此更改了本地对象的值。

要确保值持久,请按引用将值传递为:

int ABC::fun(DEF &A)
//               ^   <-- class is superfluous here