首页 > 解决方案 > 在 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);
};

最重要的是,我也在全球范围内重载了运算符:

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);

标签: c++classoperator-overloading

解决方案


推荐阅读