C:强调的是一步步操作数据的过程,这是面向过程编程
C++:面向对象编程的核心思想:封装、抽象、继承、多态
举例:模拟一个动物园,里面有不同的动物:Dog
、Cat
、Lion
。每种动物都会叫,但它们的叫声不一样。
#C语言的
#include <stdio.h>
#include <string.h>
enum AnimalType { DOG, CAT, LION };
struct Animal {
char name[20];
enum AnimalType type;
};
void speak(struct Animal* a) {
switch (a->type) {
case DOG:
printf("%s says: Woof!\n", a->name);
break;
case CAT:
printf("%s says: Meow!\n", a->name);
break;
case LION:
printf("%s says: Roar!\n", a->name);
break;
}
}
int main() {
struct Animal dog = {"Buddy", DOG};
struct Animal cat = {"Mimi", CAT};
struct Animal lion = {"Simba", LION};
speak(&dog);
speak(&cat);
speak(&lion);
return 0;
}
#所有动物放在一个结构体里,通过 type 字段区分行为。
#使用 switch-case 判断类型并执行不同代码。
#这就是面向过程 + 模拟多态,但写起来不优雅,可扩展性差
#C++的
#include <iostream>
#include <string>
using namespace std;
// 基类:Animal(抽象类)
class Animal {
public:
string name;
Animal(string n) : name(n) {}
// 虚函数,派生类会重写
virtual void speak() = 0;
};
// Dog 类继承 Animal
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {}
void speak() override {
cout << name << " says: Woof!" << endl;
}
};
// Cat 类继承 Animal
class Cat : public Animal {
public:
Cat(string n) : Animal(n) {}
void speak() override {
cout << name << " says: Meow!" << endl;
}
};
// Lion 类继承 Animal
class Lion : public Animal {
public:
Lion(string n) : Animal(n) {}
void speak() override {
cout << name << " says: Roar!" << endl;
}
};
int main() {
Animal* zoo[3];
zoo[0] = new Dog("Buddy");
zoo[1] = new Cat("Mimi");
zoo[2] = new Lion("Simba");
for (int i = 0; i < 3; i++) {
zoo[i]->speak(); // 多态调用
}
// 清理
for (int i = 0; i < 3; i++) {
delete zoo[i];
}
return 0;
}
#Animal 是一个抽象类,定义了统一接口 speak()
#Dog, Cat, Lion 分别继承并实现各自的 speak
#使用指针数组存储不同动物,统一调用 speak(),实现了真正的多态
面向过程(C) | 面向对象(C++) |
---|---|
手动判断类型 | 自动通过继承 + 多态识别类型 |
结构和函数分离 | 类中封装数据 + 方法 |
新增一种动物很麻烦 | 只需新增一个类即可 |
靠 switch 模拟行为差异 | 真正的虚函数机制 |