多型性是面向物件程式設計的重要特徵之一。多型性是指發出同樣的訊息被不同型別的物件接收時有可能導致完全不同的行為。

多型的實現方式包括以下3種:函式過載、運算子過載、虛擬函式。

1、運算子過載:

 #include<iostream>
using namespace std; class Complex
{
private:
int real,imag;
public:
void show() const;
Complex operator +(const Complex c);
Complex operator -(const Complex c);
/*
Complex(int a=0,int b=0)
{
real=a;imag=b;
}
*/
Complex(int a=,int b=):real(a),imag(b)
{}
};//don't forget this! void Complex::show() const
{
cout<<"real:"<<real<<"imag:"<<imag<<endl;
} Complex Complex::operator +(const Complex c)
{
Complex ret;
ret.real=real+c.real;
ret.imag=imag+c.imag;
return ret;
} Complex Complex::operator -(const Complex c)
{
Complex ret;
ret.real=real-c.real;
ret.imag=imag-c.imag;
return ret;
} int main()
{
Complex a(,),b(-,),c,d;
a.show();
b.show();
c=a+b;
d=a-b;
c.show();
d.show();
return ;
}

注意運算子過載運算元個數:過載為類的成員函式時,引數個數=原運算元個數-1(後置++、--除外);過載為非成員函式時,引數個數=原運算元個數,且至少有一個自定義型別。

 #include<iostream>
using namespace std; class Clock
{
private:
int hour,minute,second;
public:
Clock(int a=,int b=,int c=):hour(a),minute(b),second(c)
{
//hour=a;minute=b;second=c;
}
void show() const;
Clock operator ++();
Clock operator ++(int);
}; void Clock::show() const
{
cout<<hour<<":"<<minute<<":"<<second<<endl;
} //before
Clock Clock::operator ++()
{
if(second+>=)
{
second=second-;
if(minute+>=)
{
minute=;
if(hour+>=)
hour=;
else hour=hour+;
}
else minute=minute+;
}
else second=second+;
return *this;
} //behind still one argument
Clock Clock::operator ++(int)
{
Clock ret=*this;
++(*this);
return ret;
} int main()
{
Clock clock(,,);
cout<<"The time is:";
clock.show(); cout<<"(Time++) is:";
(clock++).show(); cout<<"(++Time) is:";
(++clock).show();
return ;
}

前置++過載,0個運算元;後置++過載,1個運算元,函式中不需要使用該運算元。

2、虛擬函式:

注意事項:若需要使用多型,則繼承方式必須是public或者protected繼承,且需要使用到的虛擬函式在基類中必須是public型別。

 #include<iostream>
using namespace std; class Base1
{
public:
virtual void show()
{
cout<<"I am base1!"<<endl;
}
}; class Base2
{
public:
void show()
{
cout<<"I am base2!"<<endl;
}
}; class Derived1:public Base1
{
void show()
{
cout<<"I am Derived1!"<<endl;
}
}; class Derived2:public Base2
{
void show()
{
cout<<"I am Derived2!"<<endl;
}
}; class Derived3:public Base1,public Base2
{
void show()
{
cout<<"I am Derived3!"<<endl;
}
}; int main()
{
Base1 *p1;
Base2 *p2;
Derived1 d1;
Derived2 d2;
Derived3 d3; p1=&d1;
p1->show(); p2=&d2;
p2->show(); p1=&d3;
p1->show();
p2=&d3;
p2->show(); return ;
}

純虛擬函式:virtual void func()=0;

抽象類:包含了純虛擬函式的類。