多态性的两种类型
- 静态多态性
- 编译时
- 静态联编
- 函数/运算符重载
- 动态多态性
- 运行时
- 动态联编
- 继承、虚函数、基类的指针或引用
- 在编译时无法确定调用的是哪个同名函数
静态多态性
缺点:不够灵活
优点:调用速度快,效率高
- 函数重载
- 同一个类中多个成员函数
- 基类和派生类中的同名函数之间
同一个类中多个成员函数
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string name;
int sort;
public:
Student();
Student(string sname, int n);
void print();
void print(int n);
};
Student::Student()
{
name = "Unknown";
sort = 18;
}
Student::Student(string sname, int n)
{
name = sname;
sort = n;
}
void Student::print()
{
cout << "Name: " << name << endl;
cout << "Sort: " << sort << endl;
}
void Student::print(int n)
{
cout<<"Number: "<< n << sort <<endl;
}
int main()
{
Student s1;
Student s2("John", 20);
s1.print();
s2.print();
s2.print(2024);
return 0;
}
基类和派生类中的同名函数之间
#include <iostream>
using namespace std;
class A
{
public:
double get_value(double a,double b)
{
return a;
}
};
class B: public A
{
public:
double get_value(double c)
{
return c;
}
};
int main()
{
A obj1;
B obj2;
cout<<obj1.get_value(2.5,3.5)<<endl;
cout<<obj2.get_value(3.2)<<endl;
cout<<obj2.A::get_value(4.7,2.6)<<endl;
return 0;
}
运算符重载
本质是函数重载
对已有 运算符赋予多重含义,同一个运算符作用于不同类型的数据将会产生不同的行为
不可以重载的运算符:
. 成员提取符
.* 成员指针运算符
:: 作用域修饰符
?: 条件运算符
sizeof 长度运算符
重载之后,运算符的优先级和结合性都不会改变
运算符重载不能改变原运算符的操作对象个数,且至少要有一个操作对象属于自定义类型
运算符重载方式:类中成员函数,类的友元函数
只能成员函数:=,(),[],->
只能友元函数:提取符>>,插入符<<
用成员函数重载运算符
第一运算对象必须是本类的对象,否则只能通过友元函数重载
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(float r = 0, float i = 0);
void print();
Complex operator + (const Complex& a);
Complex operator + (float x);
Complex operator ++ (); //单目不需要形参
};
Complex::Complex(float r, float i)
{
real = r;
imag = i;
}
void Complex::print()
{
cout << real;
if (imag != 0)
{
if (imag > 0)
cout << "+";
cout << imag << "i";
}
cout << endl;
}
Complex Complex::operator+(const Complex& a)
//形参为第二运算对象
{
Complex temp;
temp.real = real + a.real;
temp.imag = imag + a.imag;
return temp;
}
Complex Complex::operator+(float x)
{
return Complex(real+x,imag+x); //虚部和实部同时加x
}
Complex Compl