【问题标题】:Using subscript operator within a class on a template array在模板数组的类中使用下标运算符
【发布时间】:2015-12-23 12:59:25
【问题描述】:
..
..
..

const int sizes = 50;

template<class T>
class List {
private:
    int curSize;
    T arr[sizes];

public:
    List<T>(){
        cout << "constructor called\n";
        this->curSize = 0;
    }

    void add(T element) {
        arr[curSize] = element;
        this->curSize++;
    }

..
..
..

T operator[](int i){
        if( i > sizes ){
            cout << "Index out of bounds" << endl;
            return arr[0];
        }
        return arr[i];
}

当我调用 add 函数时,运算符重载对我不起作用,只有当我尝试从 main.cpp 访问它时它才起作用。 我怎样才能访问类内的运算符? 我在这里搜索,发现一个对我不起作用的灵魂乐(*this)。

【问题讨论】:

  • 您是否希望arr[curSize] 致电T operator[](int i)
  • add 函数在arr 上使用[] 运算符,它不是您的类的实例,因此不会调用重载运算符。

标签: c++ operator-overloading operator-keyword


【解决方案1】:

您使用(*this) 找到的解决方案是正确的,但是您的operator[] 返回了错误的类型,因此没有正确的使用方法。将返回值从T 更改为T&amp;

T& operator[](int i){
        if( i > sizes || i<0 ){
            cout << "Index out of bounds" << endl;
            return arr[0];
        }
        return arr[i];
}

然后你可以在你的类中使用它:

(*this)[curSize] = element;

你还应该有一个 const 版本:

T const& operator[](int i) const {
        if( i > sizes || i<0 ){
            cout << "Index out of bounds" << endl;
            return arr[0];
        }
        return arr[i];
}

编码 const 和非 const 版本(以避免重复代码)的另一种方法是使用const_cast 委托给另一个。

还要注意检查i&lt;0 的必要性。这就是将isizes 设置为unsigned 以避免额外检查的原因。优化器应该修复额外检查的明显效率低下,即使您让类型签名。但是额外的检查仍然会使源代码混乱,并且忘记它(就像你所做的那样)仍然是一个容易的错误。因此,将int 用于永远不会正确为负的值是不好的做法。

【讨论】:

    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多