1.通过虚函数实现多态性:
在父类中声明一个虚函数,然后在子类中重写该函数。当使用父类指针或引用指向子类对象并调用该虚函数时,会根据实际指向的对象类型调用相应的子类函数,从而实现多态性。
示例代码:
cpp
class Animal {
public:
virtual void makeSound() {
cout << "Animal is making a sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "Dog is barking" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() {
cout << "Cat is meowing" << endl;
}
};
int main() {
Animal* a1 = new Dog();
Animal* a2 = new Cat();
a1->makeSound(); // 输出:Dog is barking
a2->makeSound(); // 输出:Cat is meowing
delete a1;
delete a2;
return 0;
}
2.通过模板函数实现多态性:
使用模板函数可以实现函数的泛型,即一个函数可以接受不同类型的参数。通过使用模板函数,可以在编译时确定函数的具体实现,从而实现多态性。
示例代码:
cpp templatevoid swap(T& a, T& b) { T temp = a; a = b; b = temp; } int main() { int x = 1, y = 2; double d1 = 1.2, d2 = 3.4; char c1 = 'a', c2 = 'b'; swap(x, y); // 交换整数x和y的值 swap(d1, d2); // 交换浮点数d1和d2的值 swap(c1, c2); // 交换字符c1和c2的值 return 0; }