C++多态性
C++是一种基于对象的编程语言,具有许多强大的特性,包括多态性。多态性是指对象的不同性质可以表现为相同的行为。在C++中,有两种类型的多态性:编译时多态性和运行时多态性。
编译时多态性
编译时多态性是通过函数重载和模板实现的。函数重载是指在同一作用域内定义了多个名称相同但参数类型不同的函数。C++编译器会根据函数调用中的参数类型来选择调用哪个函数。例如:
void print(int num) {
cout << "Integer: " << num << endl;
}
void print(double num) {
cout << "Double: " << num << endl;
}
int main() {
int a = 5;
double b = 3.14;
print(a);
print(b);
return 0;
}
输出结果为:
Integer: 5
Double: 3.14
模板是一种通用的编程机制,可以用来创建具有相同代码结构但不同数据类型的函数或类。例如:
template<typename T>
void print(T num) {
cout << "Value: " << num << endl;
}
int main() {
int a = 5;
double b = 3.14;
print(a);
print(b);
return 0;
}
输出结果与上面的例子相同。
运行时多态性
运行时多态性是通过虚函数和继承实现的。虚函数是指在基类中声明为虚函数的函数,在派生类中可以被重写,派生类对象调用该函数时,将会调用派生类中的函数,而不是基类中的函数。例如:
class Shape {
public:
virtual void draw() {
cout << "Drawing a generic shape." << endl;
}
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle." << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle." << endl;
}
};
int main() {
Shape* shape1 = new Rectangle();
Shape* shape2 = new Circle();
shape1->draw();
shape2->draw();
return 0;
}
输出结果为:
Drawing a rectangle.
Drawing a circle.
继承是指派生类可以继承基类中的成员变量和成员函数。例如:
class Animal {
public:
void speak() {
cout << "Generic animal sound." << endl;
}
};
class Dog : public Animal {
public:
void speak() {
cout << "Bark!" << endl;
}
};
int main() {
Animal* animal1 = new Animal();
Animal* animal2 = new Dog();
animal1->speak();
animal2->speak();
return 0;
}
输出结果为:
Generic animal sound.
Bark!
应用案例
多态性可以应用于很多场景,例如图形界面编程中的控件、游戏开发中的角色和NPC等等。以下是一个简单的应用案例:
class Shape {
public:
virtual void draw() = 0;
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle." << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle." << endl;
}
};
int main() {
vector<Shape*> shapes;
shapes.push_back(new Rectangle());
shapes.push_back(new Circle());
for (int i = 0; i < shapes.size(); i++) {
shapes[i]->draw();
}
return 0;
}
输出结果为:
Drawing a rectangle.
Drawing a circle.
在此示例中,我们使用了纯虚函数和向量容器来管理多个形状对象。无论是矩形还是圆形,都可以通过调用相同的draw()函数来绘制。
总之,C++的多态性是一种非常有用的编程机制,可以提高代码的重用性和灵活性。建议在适当的情况下使用多态性来优化代码结构和提高程序效率。