setwidth()
是类的成员函数,也是类Box
的友元函数,Sbox
用于设置width
两个类的成员的值。
值width
类的Sbox
不设定/出山正常。
#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
参数通过引用传递,这意味着永远不会复制,因此sbox
内部与外部setwidth
是相同的对象。
在这里阅读:如何将对象传递给 C++ 中的函数?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句