c++ - 如何使用 C++ 中的友元函数初始化类的私有成员?
问题描述
我在 cpp 中编写了简单的代码,如下所示。我正在使用 2 种方式访问私有数据成员。首先使用 get 方法,然后使用友元函数。但是对于友元函数,我得到了对象数据成员的垃圾值。谁能告诉我如何解决这个问题?
#include<iostream>
#include<cstring>
using namespace std;
class Student
{
int roll_no;
string name;
public:
void set(int r, string n)
{
roll_no = r;
name = n;
}
void get()
{
cout<<roll_no<<" "<<name<<endl;
}
friend void access(Student s);
};
void access(Student s)
{
s.roll_no = 5;
s.name = "Shivansh";
}
int main()
{
Student s;
s.set(10,"Shrut");
s.get();
Student s1;
access(s1);
s1.get();
return 0;
}
解决方案
发生的事情是您的函数按值获取学生。(它复制它)为了修改 Student 对象,它必须通过引用来获取它。
// take it by reference to modify the Student.
void Access(Student& s) {
s.roll_no = 5;
s.name = "Shivansh";
}