c++ - 在 C++ 类中使用 const 关键字和按引用返回
问题描述
我正在关注https://www.learncpp.com/上的教程,但我有一些疑问......我有一个简单的类,其中包含许多重载运算符和一些成员函数。我不知道我应该把const放在哪里,哪个方法应该按引用返回,哪个按值返回。为简单起见,让我们说它是一个带有数字的盒子:
class Box {
private:
unsigned int d; // dimension
float *arr; // elements
public:
explicit Box(unsigned int arg_d, float* arg_arr);
Box(const Box& B);
Box() = delete;
~Box();
float _() const { return d; }
float norm() const;
Box inv() const;
Box expand(unsigned int arg_d);
Box operator~ () const;
Box operator- () const;
Box& operator= (const Box &B);
float& operator[] (unsigned int i);
const float& operator[] (unsigned int i) const;
Box& operator+= (const Box &B);
Box& operator-= (const Box &B);
Box& operator*= (const Box &B);
Box& operator^= (const unsigned int x);
Box& operator/= (const Box &B);
};
- 许多运算符(以及复制构造函数)采用const参数。我也必须编写非常量版本吗?
- 某些运算符(以及方法)在参数列表之后
_()
有一个关键字const 。我应该拥有它吗?或者我应该写两个版本的一切? - 我应该像在运算符中一样将返回类型标记为const
[]
吗?现在这个有两个版本,应该是这样吗?假设我允许使用[]
. 我什至应该写const版本吗?假设我不允许 - 我什至应该写非常量版本吗? - 与赋值链接的运算符按引用返回(我在教程中找到了)。那是对的吗?
~
其他操作符,比如-
返回新对象的操作符是否也应该通过引用返回?
最重要的是,我也在全球范围内重载了运算符:
bool operator== (const Box &B1, const Box &B2);
bool operator!= (const Box &B1, const Box &B2);
Box operator+ (const Box &B1, const Box &B2);
Box operator- (const Box &B1, const Box &B2);
Box operator* (const Box &B1, const Box &B2);
Box operator^ (const Box &B, const unsigned int x);
Box operator/ (const Box &B1, const Box &B2);
- 我是否也必须编写接受非常量参数的版本?
- 这些运算符是否应该像以前一样在末尾有const关键字?
[]
我猜不是,从那以后新对象就不能修改了?或者我是否将返回类型之前出现的const与参数列表之后的const混淆了?有什么区别? - 这些运算符是否应该通过引用返回一个新
Box
的,就像它们的赋值链对应物一样?
解决方案
推荐阅读
- istio - Istio 授权策略以排除同一命名空间中的某些应用程序
- function - 在 CPLEX 中使用什么函数,它只取大于零的值
- javascript - 如何链接 Java 代码用于进一步执行的 JavaScript webapp 应用程序生成的文件
- php - 在文件 PSD 中使用 imagick 和 php
- javascript - 需要连接d3中不同圆形打包布局的两个节点并打包布局折叠/展开
- sails.js - 在 Sails 处于生产模式时,Recaptcha POST 请求返回 Forbidden
- postgresql - 制作一个触发函数,当时间戳保存在它遇到的列中时触发
- kubernetes - kubectl 暴露部署不适用于入口控制器
- wordpress - 使用 Woocommerce 产品价格字段进行数学计算
- rest - 跨域请求在任何浏览器中被阻止,即使支持