#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[1]=1
Exception Array
Exception Array
a[2]=2
End.
The thing that is confusing me is the reasoning why the program is returning a[2] as value 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++.
a[2] = 2;
Here you invoke your operator[]
with an out-of-bounds value; it prints Exception Array
and returns a reference to aa[0]
. As such (ignoring the log message), this assignment is equivalent to a[0] = 2;
- the value of aa[0]
is now 2.
cout << "a[2]=" << a[2] << endl;
Here you again invoke the operator[]
with the same parameter; it again outputs the exception message and returns a reference to aa[0]
whose value is still 2, as assigned in the previous statement.
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. They are both out of range, so two exceptions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.