// C++多态实现的三种形式
#include <iostream>
using namespace std;
// 1. 函数重载 (Compile-time Polymorphism)
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
// 2. 运算符重载 (Compile-time Polymorphism)
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// Overload the + operator
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void print() const {
cout << "(" << real << ", " << imag << ")" << endl;
}
};
// 3. 虚函数 (Run-time Polymorphism)
class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
int main() {
// 函数重载示例
Calculator calc;
cout << "Integer addition: " << calc.add(5, 3) << endl;
cout << "Double addition: " << calc.add(5.5, 3.3) << endl;
// 运算符重载示例
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2;
cout << "Complex number addition: ";
c3.print();
// 虚函数示例
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->sound(); // 输出 "Dog barks"
animal2->sound(); // 输出 "Cat meows"
delete animal1;
delete animal2;
return 0;
}
函数重载 (Compile-time Polymorphism):
Calculator
类中,我们定义了两个 add
函数,分别用于整数和浮点数的加法。编译器在编译时根据参数类型选择合适的函数版本。运算符重载 (Compile-time Polymorphism):
Complex
类中,我们重载了 +
运算符,使得可以像操作内置类型一样对复数进行加法运算。这也是编译时多态的一种形式。虚函数 (Run-time Polymorphism):
Animal
类中,我们定义了一个虚函数 sound()
,并在其派生类 Dog
和 Cat
中重写了该函数。通过基类指针调用虚函数时,实际调用的是派生类中的版本,这是运行时多态的表现。上一篇:c++ transform
下一篇:mfc c++
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站