Programmer Defined [ ] operator.
Let's
define a class for Strings.
stringx.h
#include "string.h";
const char EOS = '\0';
class String
{
public:
String();
String( const char cstr[] );
~String();
...
char operator[] ( int index ) const;
...
private:
char* string;
int size;
};
stringx.cpp
String::String()
{
string = new char[1];
string[0] = EOS;
size = 0;
}
String::String( const char cstr[] )
{
size = strlen( cstr
);
string = new char[size+1];
strcpy(
string, cstr );
}
String::~String()
{
delete string;
}
Let's
define the [] operator for our String class.
char String::operator[]
( int index ) const
{
if ( index < 0 || index >= size )
throw out_of_range( "Index
out of range" );
return string[index];
}
See exception handling (later...) for what throw does.
app.cpp
#include "stringx.h"
void main()
{
String str(
"abcd" );
char ch = str[1];
}