-
多态:同样的消息被不同类型的对象接收时导致完全不同的行为。
-
多态分为编译时的多态和运行时的多态。
-
联编:确定操作的具体对象的过程。分静态联编和动态联编。
-
静态联编——编译和链接时进行如函数的重载、函数模板的实例化。
-
动态联编——运行时进行,通过虚函数。
运算符重载
- 不可重载的运算符(5个): . .* :: ?: sizeof
- 重载一般有两种形式:类的成员函数和非成员函数
- 成员函数运算符与友元函数运算符具有一些各自的特点:
- 一般单目运算符最好重载为成员函数,双目为友元函数
- 有一些双目不能重载为友元,如:= ,(), [ ],->
- 类型转化函数只能定义为类的成员函数。
- 若需修改对象的状态,最好为成员函数。
- 若操作符所需的操作数(特别是第一个)希望有隐式类型转换,则只能选用友元函数。
- 当重载为成员函数时,最左边的操作数必须是一个类对象。否则重载为友元函数。
- 当重载运算符的运算是可交换时,重载为友元函数。
- ++、+、-、=、->的重载:
class Complex
{
private:
double real,image;
Complex *PC;
public:
Complex(Complex * PC = NULL)
{
this->PC = PC;
}
Complex(double real = 0, double image = 0)
{
this->real = real;
this->image = image;
}
void display()
{
cout << "(" << real << "," << image << ")" << endl;
}
friend Complex operator + (Complex A, Complex B);
Complex operator - (Complex B);
Complex operator = (Complex B);
Complex operator - ();//负号;
Complex operator ++ ();
Complex operator ++ (int);
Complex * operator -> ();
};
Complex Complex::operator + (Complex A, Complex B)
{
return Complex(A.real+B.real,A.image+B.image);
}
Complex Complex::operator-(Complex B)
{
return Complex(real-B-real,image-B.image);
}
Complex Complex::operator=(Complex B)
{
real = B.real;
image = B.image;
return *this;
}
Complex Complex::operator - ()
{
return Complex(-real,-image);
}
Complex Complex::operator ++()
{
return Complex(++real,++image);
}
Complex Complex::operator ++ (int)
{
return Complex(real++,image);
}
Complex * Complex::operator -> ()
{
static Complex NullComplex(0,0);
if(PC == NULL)
return &NullComplex;
return PC;
}
- [ ]运算符的重载:
class String
{
private:
char str;
int len;
public:
char &operator [] (int n)
{
return *(str+n);
}
const char &operator[] (int n) const
{
return *(str+n);
}
};