Beruflich Dokumente
Kultur Dokumente
20
class String{
private: char * bufferPtr; int size; public: String(); String(char * ptr); void SetString(char * ptr); const char * GetString(); ... };
if we want to change the string from Ping to Pong?? {ONLY 1 character to be changed}
Possible
solution:
Call: str2.SetString(Pong); This will delete the current buffer and allocate a new one Too much overhead if string is too big
};
str1.SetChar(o, 2);
// str1 is now changed to Pong
Subscript Operator
An
Overloading
operator
Subscript Operator
int main(){ String str2; str2.SetString(Ping);
str[2] = o;
cout << str[2];
return 0;
}
Subscript Operator
class String{ ... public: char & operator[](int); ... };
Subscript Operator
char & String::operator[]( int pos){ assert(pos>0 && pos<=size); return stringPtr[pos-1]; }
Subscript Operator
int main() { String s1(Ping); cout <<str.GetString()<< endl; s1[2] = o; cout << str.GetString(); return 0;
Subscript Operator
Output:
Ping
Pong
Overloading ()
Must Any Any
be a member function
number of parameters can be specified return type can be specified can perform any generic
Operator()
operation
Function Operator
class String{ ... public: char & operator()(int); ... };
Function Operator
char & String::operator() (int pos){ assert(pos>0 && pos<=size); return bufferPtr[pos-1]; }
Subscript Operator
int main(){
String s1(Ping); char g = s1(2); s1(2) = o; // g = i
Function Operator
Output:
Pong
Function Operator
class String{ ... public: String operator()(int, int); ... };
Function Operator
String String::operator()(int index, int subLength){ assert(index>0 && index+subLength-1<=size); char * ptr = new char[subLength+1]; for (int i=0; i < subLength; ++i) ptr[i] = bufferPtr[i+index-1];
ptr[subLength] = \0;
String str(ptr); delete [] ptr; return str; }
Function Operator
int main(){ String s(Hello World);
// << is overloaded
cout << s(1, 5); return 0; }
Function Operator
Output:
Hello
Unary Operators
Unary
operators:
& * + - ++ -- ! ~
Examples:
Unary Operators
Unary ++
operators are usually prefix, except for ++ and -and -- both act as prefix and postfix
Example:
h++;
g-- + ++h - --i;
Unary Operators
General
Non-member Functions:
Friend TYPE & operator OP (TYPE & t);
Unary Operators
Overloading
unary -:
Unary Operators
Member
function definition:
temp.real = -real;
temp.img = -img; return temp; }
Unary Operators
Complex c1(1.0 , 2.0), c2; c2 = -c1;
// c2.real = -1.0
// c2.img = -2.0
Unary
way