我在組成一個問題,我不能得到預期的輸出,請幫我成分,不能得到預期的結果
#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
如果我想要預期的輸出,我應該怎麼做?
當您在調試器中運行時發現了什麼? –
另外,我只看到'cout'的兩種用法;你從哪裏得到4行輸出? –
提示:'getS()'返回一個'人'的'東西'的*副本 –