运行环境 VC6.0
运算符重载
"<<"重载
#include<iostream.h>
#include<string.h>
#define max 20
class MyString
{
public:
char *str;
MyString(char *s);
friend ostream& operator << (ostream&, MyString&);
friend MyString operator + (char *str1, MyString &mystr);
};
MyString::MyString(char *s)
{
str = new char[max];
for (int i = 0; i<max; i++)
{
str[i] = s[i];
}
}
ostream& operator << (ostream& output, MyString& mystr)
{
output << mystr.str;
return output;
}
MyString operator + (char *str1, MyString &mystr)
{
char t[max];
for (int i = 0; i<max; i++)
t[i] = str1[i];
return MyString(strcat(t, mystr.str));
}
int main()
{
MyString *s1 = new MyString("Hello");
MyString s2(" World! ");
cout << *s1 << s2 << endl;
MyString s3 = *s1;
delete s1;
cout << s3 << endl;
s3 = "abc" + s2;
cout << s3 << endl;
return 0;
}