C++多態與重載


多態與重載
重載:有兩個或多個函數名相同的函數,但是函數的形參列表不同,在調用相同函數名的函數時,根據形參列表確定到底該調用哪一個函數。
多態:同樣的消息被不同類型的對象接收時導致不同的行為。
圖一
多態性的特點
重載多態:普通函數以及類的成員函數的重載,以及運算符重載都是實例。
強制多態:將變量的類型加以變化,以符合函數或者操作的要求。
包含多態:類族中定義與不同類中的同名成員函數的多態行為。
參數多態:在使用時必須賦予實際的類型才可以實例化。
——————————————————————————————————
主要研究運算符重載和虛函數。
運算符重載
運算符重載是對已有的運算符賦予多重含義,使同一個運算符作用與不同類型的數據時導致不同的行為。
實現過程是把指定的運算表達式轉化位對運算符函數的調用,將運算對象轉化位運算符函數的實參,很具實參的類型來確定需要調用給你的函數。
語法形式
返回類型 operator 運算符(形參表)
{
函數體;
}
運算符重載為
(1)類的成員函數:函數的參數個數比原來的操作數個數要少一個。
(2)非成員函數:參數個數與原操作個數相同。
...

#include<iostream>
using namespace std;
class Clock {
public:
    Clock(int hour = 0, int minute = 0, int second = 0);
	void show()const;
	Clock& operator++();
	Clock operator++(int);
private:
	int hour, minute, second;
};
Clock::Clock(int hour, int minute, int second)
{
	if (0 <= hour && hour < 24 && 0 <= minute && minute < 60 && 0 <= second && second < 60)
	{
		this->hour = hour;
		this->minute = minute;
		this->second = second;
	}
	else
	{
		cout << "Time error!" << endl;
	}
}
void Clock::show()const {
	cout << hour << ":" << minute << ":" << second << endl;
}
Clock& Clock::operator++()  
{
	second++;
	if (second >= 60)
	{
		second -= 60;
		minute++;
		if (minute >= 60)
		{
			minute -= 60;
		hour=(hour + 1) % 24;
		}
    }
    return *this;
}
Clock Clock::operator++(int)
{
    Clock old = *this;
    ++(*this);
    return old;
}
int main()
{
	Clock myClock(3, 4, 56);
	cout << "First time:";
	myClock.show();
	cout << "Second time:";
	(myClock++).show();
	cout << "Third time:";
	(++myClock).show();
	return 0;
}   

...
運行結果:
圖一
虛函數
虛函數是動態綁定的基礎,並且虛函數必須是非靜態的成員函數。
虛函數聲明語法
virtual 函數類型 函數名(形參表);
...

#include<iostream>
using namespace std;
class Base1 {
public:
	virtual void display()const;
};
void Base1::display()const {
	cout << "Base1::display()" << endl; 
}
class Base2 :public Base1 {
public:
	void display()const;
};
void Base2::display()const {
	cout << "Base2::display()" << endl;
}
class Derived :public Base2 {
public:
	void display()const;
};
void Derived::display()const
{
	cout << "Derive::display()" << endl;
}
void fun(Base1* ptr)
{
	ptr->display();
}
int main()
{
	Base1 base1;
	Base2 base2;
	Derived derived;
	fun(&base1);
	fun(&base2);
	fun(&derived);
	return 0;
}

...
運行結果:
圖一

多態與重載的區別,重載是同名參數不同,通過參數來確定調用哪個函數;但是多態是同名同參數,通過函數的實際類型決定調用哪個函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM