为什么setter不改变C++中的值?

sda*_*das 1 c++

以下代码打印:

2
1
Run Code Online (Sandbox Code Playgroud)

代替

2
2
Run Code Online (Sandbox Code Playgroud)

为什么我的二传手没有调整价值?

主要

Vector location = camera.get_location();
camera.get_location().set_y(location.get_y() + 1);
std::cout << location.get_y() + 1 << std::endl;
std::cout << camera.get_location().get_y() << std::endl;
Run Code Online (Sandbox Code Playgroud)

camera.h

#ifndef CAMERA_H
#define CAMERA_H

#include "vector.h"

class Camera {
 private:
  Vector location;
 public:
  Vector get_location();
  void set_location(Vector);
};

#endif
Run Code Online (Sandbox Code Playgroud)

camera.cpp

#include "camera.h"

Vector Camera::get_location() { return location; }
void Camera::set_location(Vector l) { location = l; }
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 7

camera.get_location().set_y(location.get_y() + 1);
Run Code Online (Sandbox Code Playgroud)

get_location返回原始对象的副本.set_y修改也是如此,y 它正在修改原始位置的副本.如果您希望上述内容按预期工作,则返回参考:

Vector & get_location();
Run Code Online (Sandbox Code Playgroud)

功能体将与以前相同:

Vector& Camera::get_location() { return location; }
Run Code Online (Sandbox Code Playgroud)

现在它将以您期望的方式工作.

您可以将代码编写为:

Vector  & location = camera.get_location(); //save the reference
location.set_y(location.get_y() + 1);
Run Code Online (Sandbox Code Playgroud)

它修改了camera位置对象.

将上面的代码与此进行比较:

Vector location = camera.get_location(); //save the copy!
location.set_y(location.get_y() + 1);
Run Code Online (Sandbox Code Playgroud)

它不会修改camera位置对象!它修改副本,而不是原始副本.

希望有所帮助.

  • 哈!谢谢!我还是习惯了这些东西. (2认同)