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;
}
...
运⾏结果:
多态与重载的区别,重载是同名参数不同,通过参数来确定调⽤哪个函数;但是多态是同名同参数,通过函数的实际类型决定调⽤哪个函数。