在C++中,可以通过将派生类的成员函数声明为虚函数来实现多态性。然而,由于派生类的成员函数不是通过继承来实现的,所以它们不能被声明为虚函数。因此,在非虚基类中实现多态性的一种常见方法是使用指针或引用来指向基类对象,并使用基类的指针或引用来调用成员函数。
以下是一个示例代码,演示了如何在非虚基类中实现多态性:
#include<iostream>
using namespace std;
class Base {
public:
void print() {
cout << "This is the Base class." << endl;
}
};
class Derived1 : public Base {
public:
void print() {
cout << "This is the Derived1 class." << endl;
}
};
class Derived2 : public Base {
public:
void print() {
cout << "This is the Derived2 class." << endl;
}
};
int main() {
Base baseObj;
Derived1 derived1Obj;
Derived2 derived2Obj;
// 使用基类指针进行多态调用
Base* basePtr;
basePtr = &baseObj;
basePtr->print(); // 输出: This is the Base class.
basePtr = &derived1Obj;
basePtr->print(); // 输出: This is the Derived1 class.
basePtr = &derived2Obj;
basePtr->print(); // 输出: This is the Derived2 class.
return 0;
}
在上述代码中,我们创建了一个基类Base
和两个派生类Derived1
和Derived2
。然后,我们使用基类指针basePtr
来指向不同的对象,并通过该指针调用print()
函数。根据指针指向的实际对象类型,将调用相应的派生类的print()
函数。
注意,我们并没有将print()
函数声明为虚函数,而是通过基类指针来实现多态性。这是因为非虚基类的成员函数是静态绑定的,即在编译时确定调用的函数。通过使用基类指针或引用来调用成员函数,我们可以在运行时动态地选择正确的函数实现,从而实现多态性。