使用 friend 函数,我们可以覆盖 class 的私有成员吗?
Using friend function, can we overwrite the private member of the class?
在给定的 c++ 代码中,class 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();
}
下一行:
int ABC::fun(class DEF A)
您正在按值传递参数,因此更改了局部对象的值。
为确保值持久,通过引用传递值:
int ABC::fun(DEF &A)
// ^ <-- class is superfluous here
在给定的 c++ 代码中,class 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();
}
下一行:
int ABC::fun(class DEF A)
您正在按值传递参数,因此更改了局部对象的值。
为确保值持久,通过引用传递值:
int ABC::fun(DEF &A)
// ^ <-- class is superfluous here