改寫[陣列運算子問題

#include using namespace std;const int ASIZE = 10;class Safe { int* m_Array; int m_Size; public: Safe ( int sz ); virtual ~Safe (); int& operator [] ( int index ); int get ( int index ) const { return m_Array[index]; } void set ( int index, int value ) { m_Array[index] = value; } };Safe :: Safe ( int sz... show more #include
using namespace std;const int ASIZE = 10;class Safe
{
int* m_Array;
int m_Size;
public:
Safe ( int sz );
virtual ~Safe ();
int& operator [] ( int index );
int get ( int index ) const { return m_Array[index]; }
void set ( int index, int value ) { m_Array[index] = value; }
};Safe :: Safe ( int sz )
{
m_Array = new int [ sz ];
if (m_Array)
m_Size = sz;
else {
m_Size = 0;
cout << "Out of memory\n";
}
}Safe :: ~Safe ()
{
delete [] m_Array;
}static int invalid = 0;int& Safe :: operator [] ( int index )
{
if ( index < 0 || index >= m_Size) {
cout << "Out of bounds!\n";
return invalid;
}
else
return m_Array[ index ];
}void main ()
{
Safe sa ( ASIZE ); for ( int i = 0; i < ASIZE; i++ )
sa.set ( i, i);
int test1 = sa.get ( 5 );
cout << "the 5th elem is:" << test1 << endl;
int test2 = sa [ 5 ];
cout << "the 5th elem is:" << test2 << endl;
sa [ 5 ] = 11;
cout << "the 5th elem is:" << sa [ 5 ] << endl;
cout << "Attempting access out of bounds: \n";
sa [ ASIZE + 5 ] = 0;
test1 = sa [ ASIZE + 6 ];
}

請教前輩們


Q1.int* m_Array確實可以用 m_Array[index]; 這樣方式存取對吧???
因int* m_Array可以看成int m_Array[index];


Q2. if (m_Array)這事在判斷什麼???(ture or false嗎??)


Q3.當執行sa [ ASIZE + 5 ] = 0;與 test1 = sa [ ASIZE + 6 ];
時會return invalid,此時invalid的值為0,我好奇的昰這0最後return到哪去...

3 answers 3