C ++下标运算符

时间:2014-03-05 00:51:33

标签: c++ class operator-overloading subscript-operator

我写了一段代码,但似乎没有用。每次执行程序时,都会出现此错误

  

运行时检查失败#2 - 围绕变量'ary'进行堆叠   损坏

无论如何这里是我的代码(这是一个小代码)

#include <iostream>
using namespace std;

class Arrayz{
private:
    int arry[5];
public:
    Arrayz(){}
    void setInf(){
        for(int i = 0; i < 5; ++i){
            cout << "Enter age of your friends: ";
            cin >> arry[5];
        } 
    }
    const int& operator [](const int pos){
        return arry[pos];
    }
};

int main(){
    Arrayz ary;
    ary.setInf();
    cout << "Here are your friend's age: " << endl;
    for (int i = 0; i < 5; ++i){
        cout << ary[i] << endl;
    }


    return 0;
}

你也可以帮助下标操作符,我似乎不明白如何声明和使用它们。在没有首先理解程序的情况下编写程序似乎也很愚蠢,但无论如何帮助将会受到赞赏:)

2 个答案:

答案 0 :(得分:5)

您可能意味着cin >> arry[i]; - i,而不是5

答案 1 :(得分:1)

你在成员函数setInf中输入了一个拼写错误。而不是cin >> arry[5];cin >> arry[i];

void setInf(){
    for(int i = 0; i < 5; ++i){
        cout << "Enter age of your friends: ";
        cin >> arry[i];
    } 
}

至于下标运算符,那么你正确定义了它

const int& operator [](const int pos){
    return arry[pos];
}

虽然不需要使用限定符const声明参数。操作员本身也应该有限定符const你可以写简单

const int& operator [](int pos) const {
    return arry[pos];
}

int operator [](int pos) const {
    return arry[pos];
}

当用户可以更改数组arry的元素时,您也可以定义其非const版本。

int & operator []( int pos) {
    return arry[pos];
}

同样最好的是,你的类有一个会返回数组大小的成员函数。例如

class Arrayz{
private:
    static const size_t N = 5;
    int arry[N];
public:
    Arrayz(){}
    void setInf(){
        for(int i = 0; i < N; ++i){
            cout << "Enter age of your friends: ";
            cin >> arry[i];
        } 
    }
    int operator [](int pos) const {
        return arry[pos];
    }

    int & operator []( int pos) {
        return arry[pos];
    }

    size_t size() const { return N; }
};

在主要内容你可以写

for (int i = 0; i < ary.size(); ++i){
    cout << ary[i] << endl;
}