c++ - c++中的组合,得不到预期的结果

标签 c++ compiler-construction coding-style

我的作文有问题,无法得到预期的输出,请帮助我

#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

如果我想要预期的输出,我应该怎么做?

最佳答案

这个函数

something getS(){return obj_s; }

应该返回一个引用

something& getS(){return obj_s; }

因为您打算就地更改值。

关于c++ - c++中的组合,得不到预期的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17506649/

相关文章:

c++ - 显示在 QtDesigner 中创建的 QDialog

C++:传递在函数调用行中创建的数组

c++ - 惯用 std::auto_ptr 还是只使用 shared_ptr?

c++ - OpenGL:为什么我的相机上下颠倒?

C++ - 访问基类的 protected /私有(private)成员

c - 代码中的标记数量

java - gradle CompileJava任务不遵守(source | target)Compatibility属性,java.lang.UnsupportedClassVersionError:主要版本错误

java - 一个关于程序编译的问题

c# - 微软编码风格问题

python - __getattr__ 的不对称行为,新式与旧式类