簡體   English   中英

C ++例外,我只是不明白為什么輸出是它的原樣

[英]exceptions C++ , I just don't understand why the output is what it is

#include <iostream>

 using namespace std;

class Array
{
    private:
      int* a;
      int n;
    public:
        Array(int n) : n(n) {a = new int[n];};
        ~Array(){delete a;};
        int& operator[](int i)
        {
            try
            {
                if ( i < 0 || i >= n) throw 1;
                return a[i];
            }
            catch(int i)
            {
                cout << "Exception Array" << endl;
                return a[0];
            } 
        };


};



int main()
{
    Array a(2);

    try
   {
      a[0] = 1;
      cout << "a[0]=" << a[0] << endl;
      a[1] = 1;
      cout << "a[1]=" << a[1] << endl;
      a[2] = 2;
      cout << "a[2]=" << a[2] << endl;
    }
catch(int i)
{
    cout << "Exception main " << endl;
}

cout << "End. " << endl;
}

好的,輸出是這樣的:

a [0] = 1

a [1] = 1

異常數組

異常數組

a [2] = 2

結束。

讓我感到困惑的是為什么程序返回a [2]作為值2的原因? 有人可以逐步詳細地介紹如何實現這一點。 我想我對C ++中的異常不了解。

  a[2] = 2; 

在這里,您可以使用超出范圍的值來調用operator[] 它輸出Exception Array並返回對aa[0]的引用。 這樣(忽略日志消息),此分配等效於a[0] = 2; aa[0]值現在為2。

 cout << "a[2]=" << a[2] << endl; 

在這里,您再次使用相同的參數調用operator[] 它再次輸出異常消息,並返回對aa[0]的引用,該引用的值仍為2,如上一條語句中所分配。

這段代碼

a[2] = 2;
cout << "a[2]=" << a[2] << endl;

嘗試訪問a[2]兩次,一次是在賦值中,一次是在輸出語句中。 它們都超出范圍,所以有兩個例外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM