总结:
1.不能重载的运算符: . 和 .* 和 ?: 和 :: 和 sizeof 和 typeid
2.重载运算符有两种基本选择: 类的成员函数或者友元函数, 建议规则如下:
运算符 | 建议使用 |
所有一元运算符 | 成员函数 |
= () [] -> | 必须是成员函数 |
+= -= /= *= ^= &= != %= >>= <<= , 似乎带等号的都在这里了. | 成员函数 |
所有其它二元运算符, 例如: –,+,*,/ | 友元函数 |
3.前几篇中的实例,现在汇总Person类的程序:
#include <iostream>
#include <new>
#include <string>
using namespace std;
class Person
{
public:
Person();
Person(int n, const string &str);
Person(const Person &n);
Person &operator=(const Person &p);
~Person();
string getName()const;
friend ostream &operator<<(ostream &out, const Person &p);
friend istream &operator>>(istream &in, Person &p);
friend Person operator+(const Person &p1, const Person &p2);
friend bool operator==(const Person &p1, const Person &p2);
Person & operator++();
Person & operator--();
Person & operator++(int);
Person & operator--(int);
Person * operator->();
Person & operator*();
private:
int age;
string *name;
};
Person::Person():age(0), name(NULL)
{
cout << "Default Person" << endl;
}
Person::Person(int n, const string &str):age(n), name(new string(str))
{
cout << "Init Person" << endl;
}
Person::Person(const Person &n)
{
if(n.name)
{
name = new string(*(n.name));
age = n.age;
}
else
{
name = NULL;
age = 0;
}
}
Person & Person::operator=(const Person &p)
{
if(this == &p)
{
return *this;
}
string *tmp = new string(*p.name);
delete this->name;
this->name = tmp;
this->age = p.age;
cout << "operator =" << endl;
return *this;
}
Person::~Person()
{
cout << "~Person " << "name: " << name << " age: " << age << endl;
delete name;
}
string Person::getName()const
{
if(name)
{
return *name;
}
return string();
}
ostream &operator<<(ostream &out, const Person &p)
{
out << "p.age: " << p.age << ", p.name: " << p.getName();
return out;
}
istream &operator>>(istream &in, Person &p)
{
string s;
cout << "please input age and name:";
in >> p.age >> s;
if(in)
{
p.name = new string(s);
}
else
{
p = Person();
}
return in;
}
Person operator+(const Person &p1, const Person &p2)
{
string s1(*p1.name);
string s2(*p2.name);
Person p;
p.age = p1.age + p2.age;
p.name = new string(s1+s2);
return p;
}
bool operator==(const Person &p1, const Person &p2)
{
if(p1.age == p2.age && p1.name == p2.name)
{
return true;
}
return false;
}
Person & Person::operator++()
{
age++;//only ++ age
return *this;
}
Person & Person::operator--()
{
age--;
return *this;
}
Person & Person::operator++(int)
{
Person &p = *this;
age++;
return p;
}
Person & Person::operator--(int)
{
Person &p = *this;
age--;
return p;
}
Person * Person::operator->()
{
return this;
}
Person & Person::operator*()
{
return *this;
}
int main()
{
Person p1(20, "SCOTT");
Person p2(10, "Kate");
cout << p1->getName() << endl;
cout << (*p2).getName() << endl;
return 0;
}
到此,运算符重载先告一段落,以后还会继续探究更深层次的问题。