在 C++ 中,多态 的实现,除了可以使用子类的指针指向父类的对象之外,还可以通过引用来实现多态,不过引用不像 指针 灵活,指针可以随时改变指向,而引用只能指代固定的对象,在多态性方面缺乏表现力。
通过引用,实现 C++ 的多态
#include <iostream>
#include <cstring>
using namespace std;
//Person类
class Person
{
public:
Person(string name, int age):m_name(name),m_age(age)
{
}
virtual void info()
{
cout << "Call Person info, Name = " << this->m_name << " Age = " << this->m_age << endl;
}
protected:
string m_name;
int m_age;
};
class Student:public Person
{
public:
Student(string name, int age, float score):Person(name, age),m_score(score)
{
}
virtual void info()
{
cout << "Call Student info, Name = " << this->m_name << " Age = " << this->m_age << " Score = " << m_score << endl;
}
protected:
float m_score;
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Person person("HaiCoder", 18);
Student student("HaiCoder", 20, 110);
Person &rPerson = person;
Person &rStudent = student;
rPerson.info();
rStudent.info();
return 0;
}
程序运行后,控制台输出如下:
由于引用类似于常量,只能在定义的同时初始化,并且以后也要从一而终,不能再引用其他数据,所以本例中必须要定义两个引用变量,一个用来引用基类对象,一个用来引用派生类对象。从运行结果可以看出,当基类的引用指代基类对象时,调用的是基类的成员,而指代派生类对象时,调用的是派生类的成员。
即,我们使用了引用实现了多态的功能。
在 C++ 中,多态的实现,除了可以使用子类的指针指向父类的对象之外,还可以通过引用来实现多态,不过引用不像指针灵活,指针可以随时改变指向,而引用只能指代固定的对象,在多态性方面缺乏表现力。