C++问题啊请大侠指教
来源:百度知道 编辑:UC知道 时间:2024/06/04 04:21:33
//5-3.cpp
//写一个类和一个全局friend函数来处理类的private数据
#include<iostream>
using namespace std;
class firend
{
public:
firend() : x(0) {}
friend void getx(firend, int);
void show()
{
cout << x <<endl;
}
private:
int x;
};
void getx(firend f, int y)
{
f.x = y;
}
int main()
{
firend z;
int m = 6;
getx(z,m);
z.show();
return 0;
}
这个程序我我要的结果是6,为什么最后的结果是0,请高手指导下,为什么会这样
//写一个类和一个全局friend函数来处理类的private数据
#include<iostream>
using namespace std;
class firend
{
public:
firend() : x(0) {}
friend void getx(firend, int);
void show()
{
cout << x <<endl;
}
private:
int x;
};
void getx(firend f, int y)
{
f.x = y;
}
int main()
{
firend z;
int m = 6;
getx(z,m);
z.show();
return 0;
}
这个程序我我要的结果是6,为什么最后的结果是0,请高手指导下,为什么会这样
要按引用传值,否则传入getx的friend对象只是原来的一份拷贝而已:
#include<iostream>
using namespace std;
class firend
{
public:
firend() : x(0) {}
friend void getx(firend&, int);
void show()
{
cout << x <<endl;
}
private:
int x;
};
void getx(firend& f, int y)
{
f.x = y;
}
int main()
{
firend z;
int m = 6;
getx(z,m);
z.show();
return 0;
}