
所谓面向过程,以“函数/过程”为核心(函数驱动),按照函数调用顺序执行,按步骤实现功能。该思想关注的是“怎么做”。
所谓面向对象,以“对象”为核心(对象驱动),将不同的方法封装在在不同的类中,根据具体目的来调用相应的对象去实现。该思想关注的是“谁来做”。

我们来看一个通俗的例子,做一道菜:
1)面向过程思想:
按步骤执行 1.买菜 -> 2.洗菜 -> 3.切菜 -> 4. 炒菜 - > 5.装盘。
2)面向对象思想:
对象是 厨师(负责 炒菜),帮厨(负责 买菜、洗菜、切菜、装盘等),食材(包括 白菜、猪肉、鱼肉),炒锅(煮菜工具)。
这些对象各司其职,而非按步骤顺序进行。
大家是不是有直观的体会了?
02 代码比较
理解了编程思想,我们从代码层面进行解读。这里以学生成绩管理功能为例:
1)C语言(面向过程)
#include<iostream>#include<string>using namespace std;// 定义数据结构:存储学生信息(仅数据,无行为)struct Student {string name; // 姓名int id; // 学号int scores[3]; // 3门课成绩};// 函数1:计算总分(操作外部的Student数据)intcalculateTotalScore(const Student& stu){int total = 0;for (int score : stu.scores) {total += score;}return total;}// 函数2:打印学生信息(操作外部的Student数据)voidprintStudentInfo(const Student& stu){int total = calculateTotalScore(stu);cout << "学号:" << stu.id << endl;cout << "姓名:" << stu.name << endl;cout << "总分:" << total << endl;}intmain(){// 步骤1:定义数据Student stu;stu.name = "zgh";stu.id = 2025001;stu.scores[0] = 85;stu.scores[1] = 90;stu.scores[2] = 78;// 步骤2:按顺序调用函数(过程化执行)printStudentInfo(stu);return 0;}
从上述C代码中可以看出:数据与操作数据的函数相互隔离,顺序执行
#include <iostream>#include <string>using namespace std;// 定义类:封装学生的属性和方法class Student {private:// 私有属性:仅类内部可访问(封装性)string name;int id;int scores[3];public:// 构造函数:初始化对象属性Student(string n, int i, int s1, int s2, int s3) {name = n;id = i;scores[0] = s1;scores[1] = s2;scores[2] = s3;}// 方法1:计算总分(类内部方法,访问私有属性)intcalculateTotalScore() const {int total = 0;for (int score : scores) {total += score;}return total;}// 方法2:打印信息(类内部方法)voidprintInfo() const {int total = calculateTotalScore();cout << "学号:" << id << endl;cout << "姓名:" << name << endl;cout << "总分:" << total << endl;}// 可选:提供接口修改属性(封装的扩展,避免直接操作私有数据)voidsetScore(int index, int newScore) {if (index >= 0 && index < 3) {scores[index] = newScore;}}};intmain() {// 创建对象:通过类实例化,属性通过构造函数初始化Student stu("zgh", 2025001, 85, 90, 78);// 调用对象的方法:对象自主完成行为(“谁来做”)stu.printInfo();// 扩展:修改成绩(通过类提供的接口,保证数据安全)stu.setScore(2, 88);cout << "\n修改第3门成绩后:" << endl;stu.printInfo();return 0;}
从上述C++代码中可以看出:将数据与行为封装为一个类,绑定在一起
数据(name、score、id)私有化,避免被外部非法纂改;
数据与行为(计算、打印成绩等)绑定在一个类中,封装化;
新增功能只需在类内新增方法,不影响外部代码。
03 不同适用场景
1)C语言(面向过程编程)适用于嵌入式开发、底层库开发、操作系统内核开发等。
2)C++(面向对象编程)适用于大型工程、需模块化的复杂系统、跨平台开发。
写在最后
如果有童鞋想入门C++,可参考小栈之前的文章:别再怕 C++!入门其实很简单
你在从 C 转 C++ 的过程中,最头疼的思想卡点是什么?欢迎评论区滴滴!