简体   繁体   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;
}

Okay, so the output is this: 好的,输出是这样的:

a[0]=1 a [0] = 1

a[1]=1 a [1] = 1

Exception Array 异常数组

Exception Array 异常数组

a[2]=2 a [2] = 2

End. 结束。

The thing that is confusing me is the reasoning why the program is returning a[2] as value 2? 让我感到困惑的是为什么程序返回a [2]作为值2的原因? Can someone go into more detail as to how this is achieved, step by step. 有人可以逐步详细地介绍如何实现这一点。 I think I am not understanding something about exceptions in C++. 我想我对C ++中的异常不了解。

  a[2] = 2; 

Here you invoke your operator[] with an out-of-bounds value; 在这里,您可以使用超出范围的值来调用operator[] it prints Exception Array and returns a reference to aa[0] . 它输出Exception Array并返回对aa[0]的引用。 As such (ignoring the log message), this assignment is equivalent to a[0] = 2; 这样(忽略日志消息),此分配等效于a[0] = 2; - the value of aa[0] is now 2. aa[0]值现在为2。

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

Here you again invoke the operator[] with the same parameter; 在这里,您再次使用相同的参数调用operator[] it again outputs the exception message and returns a reference to aa[0] whose value is still 2, as assigned in the previous statement. 它再次输出异常消息,并返回对aa[0]的引用,该引用的值仍为2,如上一条语句中所分配。

This code 这段代码

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

tries to access a[2] twice, once in the assignment and once in the output statement. 尝试访问a[2]两次,一次是在赋值中,一次是在输出语句中。 They are both out of range, so two exceptions. 它们都超出范围,所以有两个例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM