Jun 23, 2011 at 12:06am UTC
what would you want to happen in these cases? What types of class is 'object' an instance of? Since you want to overload [] im guessing 'object' is not an array but be careful when considering overloading an operator, you should only overload if the meaning of the operation remains clear, otherwise create a clearly named method to perform the operation.
Last edited on Jun 23, 2011 at 12:08am UTC
Jun 23, 2011 at 12:25am UTC
You need to be more specific. I'm going to take a shot in the dark and suggest this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
class OBJECT
{
public :
OBJECT( void );
~OBJECT( void );
protected :
struct INFORMATION
{
int _iLength;
int *_pResources;
} _Info;
public :
int &operator [ ] ( const int iIndex ) const ;
};
OBJECT::OBJECT( void )
{
try
{
// Attempt to allocate a block of memory.
this ->_Info._pResources = ( new int [ 5 ] );
for ( int iLoop( 0 ); iLoop < 5; iLoop++ )
// Any initializing value will do here.
this ->_Info._pResources[ iLoop ] = ( iLoop + 2 );
this ->_Info._iLength = 5;
}
catch ( std::bad_alloc )
{
this ->_Info._pResources = NULL;
this ->_Info._iLength = 0;
}
}
OBJECT::~OBJECT( void )
{
delete [ ] this ->_Info._pResources;
}
int &OBJECT::operator [ ] ( const int iIndex ) const
{
// Check if the allocator is in use.
if ( !this ->_Info._pResources )
// Throw an exception or something...
// Validate the index.
if ( ( iIndex >= 0 ) && ( iIndex <= ( this ->_Info._iLength - 1 ) ) )
return this ->_Info._pResources[ iIndex ];
else
// Throw an exception here or something...
}
int main( )
{
OBJECT Object;
Object[ 0 ] = 45;
std::cin.get( );
return 0;
}
This is what I've come up with, and it
might help you. Without more information, I cannot give much help.
Wazzak
Last edited on Jun 23, 2011 at 12:46am UTC
Jun 23, 2011 at 4:33am UTC
If you want to store multiple data types at once you might consider a struct.
struct name
{
int intArray[]
char charArray[]
etc...
};
Jun 23, 2011 at 7:01am UTC
I think you misread the original post, Edithsong.
Wazzak