我的构图有问题,我无法得到预期的输出,请帮助我
#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
如果我想要预期的输出,我应该怎么做?