一个完整的类,需要有:一般构造函数、拷贝构造函数、赋值函数,涉及数据存储的,还应该对移位运算符进行重载。
同时对一个运算符进行重载及友元重载时,调用顺序为先重载,后友元重载。
#include <iostream.h>
#include <string.h>
#include <stdio.h>
class Person
{
friend ostream& operator << (ostream& s, const Person& obj); // declaration of overriding operator << function
friend istream& operator >> (istream& s, Person& obj); // declaration of overriding operator >> function
private:
char* name;
public:
Person (char* n = "") // default constructor
{
name = new char[strlen (n) + 1];
strcpy (name, n);
}
Person (const Person& per) // copy constructor
{
name = new char[strlen (per.name) + 1];
strcpy (name, per.name);
}
Person& operator = (const Person& per) // #1 overriding assignment function
{
if == ( this & per ) // prevent copy itself
return *this;
delete[] name;
name = new char[strlen (per.name) + 1];
strcpy (name, per.name);
return *this;
}
Person& operator = (char* n) // #2 overriding assignment function - typer conversion
{
delete[] name;
name = new char[strlen (n) + 1];
strcpy (name, n);
return *this;
}
~Person () // destructor
{
delete[] name;
}
};
ostream& operator << (ostream& s, const Person& obj) // definition of ...
{
s << obj.name << endl;
return s;
}
istream& operator >> (istream& s, Person& obj) // definition of ...
{
char cs[128];
s >> cs;
if (strlen (obj.name) < strlen (cs))
{
delete[] obj.name;
obj.name = new char[strlen (cs) + 1];
}
strcpy (obj.name, cs);
return s;
}
int main (void)
{
Person a ("Xiaozhang"); // provoke default constructor
Person b = "Xiaoli"; // provoke default constructor
Person c (b); // provoke copy constructor
c = a; // provoke overriding assignment function - typer conversion
c = "Laoadfffadfli"; // provoke overriding assignment function - typer conversion
cin >> b; // provoke overriding operator >> function - typer conversion
Person d;
cin >> d;
d = d; // verify self copy
return 0;
}