gpt4 book ai didi

c++ - 运算符重载函数的参数什么时候应该通过常量引用传递?

转载 作者:行者123 更新时间:2023-11-30 03:57:48 26 4
gpt4 key购买 nike

lhs 和 rhs 通过常量引用 (const Type&) 传递。

CVector operator+ (const CVector& lhs, const CVector& rhs) {
CVector temp;
temp.x = lhs.x + rhs.x;
temp.y = lhs.y + rhs.y;
return temp;
}

最佳答案

  1. 当要复制的数据是轻量级(廉价)数据时(例如,对于 int、float、char 等。按值传递就可以了)

  2. 参数在函数/运算符实现中被观察到(即它是一个输入只读参数)

作为对这两点的总结,您将得到我们将明白为什么我们应该通过常量引用传递。

要清楚理解,请参阅 http://www.cs.fsu.edu/~myers/c++/notes/references.html

关于c++ - 运算符重载函数的参数什么时候应该通过常量引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com