通过作为另一个 class 的成员函数的友元函数设置值
Setting a value by a friend function which is a member function of another class
setwidth()
是classBox
的成员函数,也是classSbox
的友元函数,就是设置成员的值width
两个 classes.
class Sbox
的 width
的值未 setting/coming 正确输出。
#include<iostream>
using namespace std;
class Sbox;
class Box{
private:
double width;
public:
friend void printwidth(Box box);
void setwidth(Sbox sbox, double wid);
};
class Sbox {
private:
double width;
public:
friend void Box::setwidth(Sbox sbox, double wid);
void printwidth() {
cout << "the width of small box: " << width; //this value is coming wrong
}
};
void Box::setwidth(Sbox sbox, double wid) {
width = wid;
sbox.width = wid;
}
void printwidth(Box box) {
cout << "width of the box: " << box.width << endl;
}
int main() {
Box box;
Sbox sbox;
box.setwidth(sbox, 10.77);
printwidth(box);
sbox.printwidth();
return 0;
}
您需要通过引用传入 Sbox。将 & 符号添加到这三行。
void setwidth(Sbox& sbox,double wid);
friend void Box::setwidth(Sbox& sbox,double wid);
void Box::setwidth(Sbox& sbox,double wid)
您按值传递了 sbox
,这意味着制作了一个副本以供在 setwidth
中使用。然后,您的代码更改了 sbox
副本的宽度,但该副本随后在 setwidth
的末尾被销毁,而函数外的原始 sbox
保持不变。
添加&
意味着Sbox
参数通过引用传递,这意味着永远不会进行复制,所以setwidth
里面的sbox
是和外面那个一样的东西
阅读此处:How to pass objects to functions in C++?
setwidth()
是classBox
的成员函数,也是classSbox
的友元函数,就是设置成员的值width
两个 classes.
class Sbox
的 width
的值未 setting/coming 正确输出。
#include<iostream>
using namespace std;
class Sbox;
class Box{
private:
double width;
public:
friend void printwidth(Box box);
void setwidth(Sbox sbox, double wid);
};
class Sbox {
private:
double width;
public:
friend void Box::setwidth(Sbox sbox, double wid);
void printwidth() {
cout << "the width of small box: " << width; //this value is coming wrong
}
};
void Box::setwidth(Sbox sbox, double wid) {
width = wid;
sbox.width = wid;
}
void printwidth(Box box) {
cout << "width of the box: " << box.width << endl;
}
int main() {
Box box;
Sbox sbox;
box.setwidth(sbox, 10.77);
printwidth(box);
sbox.printwidth();
return 0;
}
您需要通过引用传入 Sbox。将 & 符号添加到这三行。
void setwidth(Sbox& sbox,double wid);
friend void Box::setwidth(Sbox& sbox,double wid);
void Box::setwidth(Sbox& sbox,double wid)
您按值传递了 sbox
,这意味着制作了一个副本以供在 setwidth
中使用。然后,您的代码更改了 sbox
副本的宽度,但该副本随后在 setwidth
的末尾被销毁,而函数外的原始 sbox
保持不变。
添加&
意味着Sbox
参数通过引用传递,这意味着永远不会进行复制,所以setwidth
里面的sbox
是和外面那个一样的东西
阅读此处:How to pass objects to functions in C++?