一樣的消息被不一樣類型的對象接收時致使的不一樣的行爲。對加法而言,若是是浮點數和整型數據相加,就要先將整型轉換爲浮點型在進行加法運算,這就是典型的多態。ios
編譯過程當中肯定同名操做的對象。c++
在程序運行過程當中動態肯定操做所指具體對象。函數
改變現有運算符的操做方式,以用於類類型,使得程序看起來更直觀。this
a.只能重載c++已有的運算符(除了少數幾個外均可以重載)。
b.重載以後運算符的優先級和結合性不變。
c.通常來講,重載的功能與原有功能相似,不能改變原運算符的操做對象個數,同時至少要有一個操做對象是自定義類型。
d.規定:類屬關係運算符".",成員指針運算符".*",做用域分辨符"::",三目運算符"?:"是不能重載的。spa
返回類型 operator 運算符(形參表) { 函數體 }
函數的參數個數比原來的操做數個數少一個(後置"++","--"除外)。由於第一個操做數會被做爲函數調用的目的對象,函數體中能夠直接訪問第一個操做數成員。指針
#include"pch.h" #include<iostream> using namespace std; class Point//定義一個Point類 { public: Point(int x,int y):x(x),y(y) {} //前置,單目運算因此沒有形參 //前置實現以後結果是左值,而且在實現的時候要實現數據共享,因此傳引用 Point& operator++(); Point& operator--(); //後置,有一個int參數僅用於區分前置與後置 Point operator++(int); Point operator--(int); void show() { cout << "the result is " << x <<";"<<y<< endl; } private: int x,y; }; //類的非靜態函數成員實現 Point& Point::operator++() { x++; y++; return *this; } Point& Point::operator--() { x--; y--; return *this; } Point Point::operator++(int) { Point old = *this; x++; y++; return old; } Point Point::operator--(int) { Point old = *this; x--; y--; return old; } int main() { Point po(6,7); po++.show();//6,7 po--.show();//7,8 po.show();//6,7 (--po).show();//5,6 (++po).show();//6,7 return 0; }
返回類型 operator 運算符(形參表) { 函數體 }
在實現運算符重載時,有時須要訪問運算符參數所涉及類的私有成員,這時能夠把該函數聲明爲類的友元函數。code
參數個數與原操做數個數相同。對象
#include"pch.h" #include<iostream> using namespace std; class Complex { public: Complex(double real=0.0, double image=0.0) :real(real), image(image) { } //友元函數實現 friend Complex& operator++(Complex &c1); friend Complex operator++(Complex &c1,int); void show() { cout << "(" << real << "," << image << ")" << endl; } private: double real, image; }; Complex& operator++(Complex &c1) { c1.real++; c1.image++; return c1; } Complex operator++(Complex &c1, int) { Complex c2 = c1; ++(c1); return c2; } int main() { Complex a(3.0, 4.0); Complex b(2.0, 5.0); (b++).show();//2,5 b.show();//3,6 (++a).show();//4,5 return 0; }
爲了正確的調用對象的析構函數,通常要求具備層次結構的最原始的基類的析構函數定義爲虛函數,由於在delete一個抽象類指針的時候,必需要經過虛函數才能找到真正的析構函數。blog
#include"pch.h" #include<iostream> using namespace std; class Base { public: Base() {} virtual ~Base()//虛析構函數 { cout << "destrutor of Base" << endl; } }; class Derived :public Base { public: Derived() {} ~Derived() { cout << "destrutor of Derived" << endl; } }; int main() { //先生成Base對象,而後生成Derived對象,返回派生類地址給基類指針 Base *p = NULL; p = new Derived; delete p; return 0; }
結果展現
接口
若是基類析構函數不是虛函數,則不會動態綁定到派生類的析構函數。若是上述基類的析構函數不是虛函數,則有
帶有純虛函數的類。它的主要做用是經過它爲一個類族創建一個公有的接口,使它們可以更有效地發揮多態特性。
若是派生類給出全部純虛函數的實現,這個派生類就能夠定義本身的對象,於是再也不是抽象類;若是派生類並無給出全部純虛函數的實現,這時的派生類仍然是一個抽象類。
不能對其實例化。也就是說不能定義一個抽象類的對象,可是能夠定義一個抽象類的指針和引用。
virtual 函數類型 函數名(參數表)=0;
若是將析構函數聲明爲純虛函數,必須給出它的實現,由於派生類的析構函數體執行完後須要調用基類的純虛函數。