为什么第二个程序的输出与第一个程序不同?

 朱美萍客户 发布于 2023-02-13 22:12

返回对调用该函数的对象的引用时,返回的引用可用于链接单个对象上的函数调用.

在这里,我正在应用相同的概念.但是如果我以不同方式初始化对象,我会得到不同的输出.

第一个例子:

#include
using namespace std;

class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test &setX(int a) { x = a; return *this; }
  Test &setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
  Test obj1(5, 5);

  // Chained function calls.  All calls modify the same object
  // as the same object is returned by reference
  obj1.setX(10).setY(20);

  obj1.print();
  return 0;
}

输出为10和20,这是正确的.

但是,第二个示例的输出不正确:

#include
using namespace std;

class Test
{
private:
  int x;
  int y;
public:
  Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test setX(int a) { x = a; return *this; }
  Test setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
  Test obj1;
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}

输出为10和0.

为什么?我认为两者都是一样的,第二个程序的输出也应该是10和20.它有什么不同?

1 个回答
  • 不同之处在于程序的第二个版本按值返回.这意味着第二次调用(即setY)是在副本上执行obj1,而不是在obj1自身上执行.这就是为什么X最终只能被设定,但不是Y.

    另一方面,在您的第一个程序中,setter将其结果作为参考返回.这意味着没有复制,因此setY在同一个对象上调用setX,而不是在其副本上调用.

    2023-02-13 22:31 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有