我的构图有问题,我无法得到预期的输出,请帮帮我
#include <iostream>
using namespace std;
class something{
int length;
public :
something(){length = 0;}
something(int l){length = l;}
void setLength(int l){length = l;}
int getLength(){return length;}
};
class person{
int age;
something obj_s;
public:
person(int i){age = i;}
void setS(int length)
{
something temp(length);
obj_s = temp;
}
something getS(){return obj_s; }
};
int main()
{
person p(20);
cout<<p.getS().getLength()<<endl;
p.getS().setLength(20); //--------change at here---------
cout<<p.getS().getLength()<<endl;
//--------------------------------------------------------
person w(20);
w.setS(5);
cout<<w.getS().getLength()<<endl;
w.getS().setLength(20); //--------change at here---------
cout<<w.getS().getLength()<<endl;
return 0;
}
输出是:
0
0
5
5
为什么不:(预期产出)
0
20
5
20
如果我想要预期的输出,我该怎么办?
答案 0 :(得分:4)
此功能
something getS(){return obj_s; }
应该返回引用
something& getS(){return obj_s; }
因为您打算就地更改该值。