【问题标题】:C++ Subscript operatorC++ 下标运算符
【发布时间】:2014-03-05 00:51:33
【问题描述】:

我已经编写了一个代码,但它似乎不起作用。每次执行程序都会出现这个错误

运行时检查失败 #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;
}

你也可以帮助下标运算符,我似乎不明白如何声明和使用它们。另外,在没有首先理解程序的情况下编写程序似乎很愚蠢,但无论如何,我们将不胜感激:)

【问题讨论】:

  • cin &gt;&gt; arry[5] a) 超出范围,b) 尽管处于循环中,但它始终是相同的索引(5 应该是 i)

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


【解决方案1】:

您可能指的是cin &gt;&gt; arry[i];i,而不是5

【讨论】:

    【解决方案2】:

    您在成员函数 setInf 中输入错误。应该用cin &gt;&gt; arry[i];代替cin &gt;&gt; arry[5];

    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];
    }
    

    当用户可以更改数组的元素时,您还可以定义其非常量版本。

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

    而在 main 你可以写

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2015-11-04
      • 2012-06-21
      • 2017-10-12
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多