C++:多态性

多态性的两种类型

  • 静态多态性
    • 编译时
    • 静态联编
    • 函数/运算符重载
  • 动态多态性
    • 运行时
    • 动态联编
    • 继承、虚函数、基类的指针或引用
    • 在编译时无法确定调用的是哪个同名函数

静态多态性

缺点:不够灵活

优点:调用速度快,效率高

  • 函数重载
    • 同一个类中多个成员函数
    • 基类和派生类中的同名函数之间

 同一个类中多个成员函数

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tsglz3210

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值