无法使用朋友 class 更改 class 的私有成员的值
Can't change the value of private member of a class using friend class
所以我试图学习如何使用朋友 class 更改私有 class 成员的值,但朋友 class 无法更改主要 class,这是我完成的代码,我是编码领域的新手,请帮助我:)
#include <iostream>
using namespace std;
class A {
private:
int marks;
public:
show_marks()
{
cout <<marks;
}
set_marks( int num )
{
marks =num;
}
friend class B;
};
class B{
public:
show_A_marks(A teacher, int num){
teacher.marks= num;
}
};
int main(){
A teacher;
teacher.set_marks(10);
teacher.show_marks();
cout <<endl;
B student;
student.show_A_marks(teacher,20);
teacher.show_marks();
}
-这应该打印:
10
20
但正在打印:
10
10
在函数中:
show_A_marks(A teacher, int num)
您正在按值传递 teacher
。您正在制作该值的副本,并编辑该副本。当函数returns时,copy就没有了。您需要通过引用传递它:
show_A_marks(A& teacher, int num)
// ^ reference to A
有关详细信息,请参阅 What's the difference between passing by reference vs. passing by value?。
所以我试图学习如何使用朋友 class 更改私有 class 成员的值,但朋友 class 无法更改主要 class,这是我完成的代码,我是编码领域的新手,请帮助我:)
#include <iostream>
using namespace std;
class A {
private:
int marks;
public:
show_marks()
{
cout <<marks;
}
set_marks( int num )
{
marks =num;
}
friend class B;
};
class B{
public:
show_A_marks(A teacher, int num){
teacher.marks= num;
}
};
int main(){
A teacher;
teacher.set_marks(10);
teacher.show_marks();
cout <<endl;
B student;
student.show_A_marks(teacher,20);
teacher.show_marks();
}
-这应该打印: 10 20 但正在打印: 10 10
在函数中:
show_A_marks(A teacher, int num)
您正在按值传递 teacher
。您正在制作该值的副本,并编辑该副本。当函数returns时,copy就没有了。您需要通过引用传递它:
show_A_marks(A& teacher, int num)
// ^ reference to A
有关详细信息,请参阅 What's the difference between passing by reference vs. passing by value?。