如何解决在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 吗?现在,这个有两个版本,应该是这样吗?假设我允许使用[]
修改class元素。我是否应该编写 const 版本?假设我不允许-我是否应该编写 non-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
?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。