news 2026/4/15 9:50:47

【C++类与对象·上】从结构体到类:C++封装思想入门

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【C++类与对象·上】从结构体到类:C++封装思想入门

在C语言中,struct仅能打包数据:

代码语言:javascript

AI代码解释

// C语言风格 struct Student { char name[20]; int age; float score; };

C++让struct脱胎换骨,不仅能包含数据,还能拥有"行为"(方法):

代码语言:javascript

AI代码解释

struct Student { char name[20]; int age; // 方法!C语言无法做到 void introduce() { std::cout << "我是" << name << ",今年" << age << "岁\n"; } };

更关键的是,C++引入了class关键字,它与struct几乎相同,唯一区别是默认访问权限

  • class默认成员为private(私有)
  • struct默认成员为public(公有)

踩坑经历:刚学C++时,我常常忘记在class中添加public关键字,导致所有成员函数都无法在类外调用,编译器报错看得我一头雾水。后来才明白,C++的设计哲学是"默认保守"——除非明确声明,否则不对外开放。

封装:数据与行为的完美融合

封装是面向对象的基石。它像保险箱一样保护内部数据,只通过特定"钥匙孔"(接口)与外界交互。我们用publicprivate访问限定符实现这一思想:

代码语言:javascript

AI代码解释

class BankAccount { private: double balance; // 私有成员,外部无法直接访问 public: // 公有接口,控制对私有数据的访问 void deposit(double amount) { if (amount > 0) balance += amount; } bool withdraw(double amount) { if (amount > 0 && balance >= amount) { balance -= amount; return true; } return false; } double getBalance() const { return balance; } };

这种设计有两大优势:

  1. 数据安全:防止外部代码直接修改balance,避免设置为负数等非法操作
  2. 行为封装:将相关操作(存款、取款)与数据绑定在一起,代码更清晰
代码演示:银行账户类,展示封装的力量

代码语言:javascript

AI代码解释

#include <iostream> using namespace std; class BankAccount { private: string accountNumber; double balance; public: // 构造函数:初始化账户 BankAccount(string number, double initialBalance = 0.0) : accountNumber(number), balance(initialBalance) { cout << "账户 " << accountNumber << " 已创建,初始余额: " << balance << endl; } // 存款 void deposit(double amount) { if (amount <= 0) { cout << "错误:存款金额必须大于0" << endl; return; } balance += amount; cout << "存入 " << amount << ",新余额: " << balance << endl; } // 取款 bool withdraw(double amount) { if (amount <= 0) { cout << "错误:取款金额必须大于0" << endl; return false; } if (balance < amount) { cout << "错误:余额不足,当前余额: " << balance << endl; return false; } balance -= amount; cout << "取出 " << amount << ",新余额: " << balance << endl; return true; } // 获取余额 double getBalance() const { return balance; } // 显示账户信息 void display() const { cout << "账户: " << accountNumber << ", 余额: " << balance << endl; } }; int main() { // 创建账户 BankAccount account1("ACCT-001", 1000.0); account1.display(); // 存款 account1.deposit(500.0); // 取款 account1.withdraw(200.0); // 尝试非法操作(无法直接访问私有成员) // account1.balance = -10000; // 编译错误!无法访问私有成员 cout << "当前余额: " << account1.getBalance() << endl; return 0; }

类域与成员函数

当你在类内定义函数时,编译器会为每个成员函数隐式添加一个this指针作为第一个参数。这个指针指向调用函数的对象本身,让我们能在函数内部访问对象的成员变量。

代码语言:javascript

AI代码解释

class Rectangle { private: int width, height; public: void setSize(int width, int height) { // this->width 指成员变量,width指参数 this->width = width; this->height = height; } };

this指针是C++实现面向对象的关键机制,它让我们可以在同一个类的多个对象之间区分各自的成员变量。当你调用obj.method()时,编译器将其转换为method(&obj),隐式传递对象地址。

易错点警告:如果你尝试通过空指针调用成员函数,当函数内部使用了成员变量时会导致程序崩溃。但如果成员函数不访问任何成员变量,空指针调用可能"侥幸"成功,这是危险的未定义行为!

www.dongchedi.com/article/7594907272338391577
www.dongchedi.com/article/7594906883010921022
www.dongchedi.com/article/7594905551013265982
www.dongchedi.com/article/7594904583437648409
www.dongchedi.com/article/7594903316430275134
www.dongchedi.com/article/7594903056937206296
www.dongchedi.com/article/7594901837732512318
www.dongchedi.com/article/7594901098721427993
www.dongchedi.com/article/7594900396469322265
www.dongchedi.com/article/7594899476994163224
www.dongchedi.com/article/7594900087831085593
www.dongchedi.com/article/7594898822019744280
www.dongchedi.com/article/7594899523533996569
www.dongchedi.com/article/7594899750689145406
www.dongchedi.com/article/7594897483562828350
www.dongchedi.com/article/7594898207591711257
www.dongchedi.com/article/7594896653753565720
www.dongchedi.com/article/7594898207591809561
www.dongchedi.com/article/7594896961158349374
www.dongchedi.com/article/7594897178171327001
www.dongchedi.com/article/7594897178171523609
www.dongchedi.com/article/7594895915098718745
www.dongchedi.com/article/7594894897057317400
www.dongchedi.com/article/7594894386924700222
www.dongchedi.com/article/7594895162640433726
www.dongchedi.com/article/7594893333349466649
www.dongchedi.com/article/7594893449250783806
www.dongchedi.com/article/7594894572120343065
www.dongchedi.com/article/7594870233123340825
www.dongchedi.com/article/7594914712018600510
www.dongchedi.com/article/7594913283375907352
www.dongchedi.com/article/7594914016129106456
www.dongchedi.com/article/7594914424213766718
www.dongchedi.com/article/7594913083894891033
www.dongchedi.com/article/7594913119710069310
www.dongchedi.com/article/7594912459706696254
www.dongchedi.com/article/7594911633613390360
www.dongchedi.com/article/7594909036307595800
www.dongchedi.com/article/7594910057444786750
www.dongchedi.com/article/7594909893274927641
www.dongchedi.com/article/7594909974816588350
www.dongchedi.com/article/7594909035217404441
www.dongchedi.com/article/7594908551181615678
www.dongchedi.com/article/7594906883010855486
www.dongchedi.com/article/7594907513641058878
www.dongchedi.com/article/7594905549272285720
www.dongchedi.com/article/7594906861996884505
www.dongchedi.com/article/7594906134906421785
www.dongchedi.com/article/7594905869373096472
www.dongchedi.com/article/7594904114086560281
www.dongchedi.com/article/7594903301414650392
www.dongchedi.com/article/7594901235942228542
www.dongchedi.com/article/7594901805579452953
www.dongchedi.com/article/7594900315275657752
www.dongchedi.com/article/7594899458794799641
www.dongchedi.com/article/7594900266315645465
www.dongchedi.com/article/7594900151853236798
www.dongchedi.com/article/7594898846111580697
www.dongchedi.com/article/7594899021756776984
www.dongchedi.com/article/7594897166766965272
www.dongchedi.com/article/7594897310665245246
www.dongchedi.com/article/7594897192310407705
www.dongchedi.com/article/7594897631617794585
www.dongchedi.com/article/7594896580080435737
www.dongchedi.com/article/7594895704896684568
www.dongchedi.com/article/7594897374330503705
www.dongchedi.com/article/7594895618720449048

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/31 21:51:44

ARM处理器模式切换深度剖析

ARM处理器模式切换&#xff1a;从异常响应到系统安全的底层逻辑你有没有遇到过这样的场景&#xff1f;一个嵌入式系统在运行中突然卡死&#xff0c;调试器显示程序“莫名其妙”跳进了Data Abort处理函数&#xff1b;或者你在写Bootloader时&#xff0c;发现SVC指令根本没触发预…

作者头像 李华
网站建设 2026/4/12 16:43:09

STLink驱动安装:STM32开发必备手把手教程

STLink驱动安装&#xff1a;STM32开发必备手把手教程 从一块Nucleo板说起——为什么我连不上STM32&#xff1f; 你有没有过这样的经历&#xff1f; 满怀期待地打开新买的Nucleo开发板&#xff0c;USB线一插&#xff0c;准备烧录第一个“Hello World”程序&#xff0c;结果ST…

作者头像 李华
网站建设 2026/4/7 17:27:42

元宇宙开发利器:用Holistic Tracking镜像快速实现数字人驱动

元宇宙开发利器&#xff1a;用Holistic Tracking镜像快速实现数字人驱动 1. 引言&#xff1a;数字人驱动的技术演进与核心挑战 随着元宇宙概念的持续升温&#xff0c;虚拟数字人作为人机交互的核心载体&#xff0c;正在从游戏、直播向教育、客服、电商等多领域渗透。而实现自…

作者头像 李华
网站建设 2026/4/15 8:53:30

DLSS Swapper终极指南:解锁游戏性能新高度

DLSS Swapper终极指南&#xff1a;解锁游戏性能新高度 【免费下载链接】dlss-swapper 项目地址: https://gitcode.com/GitHub_Trending/dl/dlss-swapper 还在为游戏卡顿而烦恼&#xff1f;面对眼花缭乱的DLSS版本不知如何选择&#xff1f;别担心&#xff0c;DLSS Swapp…

作者头像 李华
网站建设 2026/4/5 23:39:42

DLSS Swapper终极升级指南:一键替换DLSS版本完整教程

DLSS Swapper终极升级指南&#xff1a;一键替换DLSS版本完整教程 【免费下载链接】dlss-swapper 项目地址: https://gitcode.com/GitHub_Trending/dl/dlss-swapper 想要轻松升级游戏DLSS版本&#xff0c;获得更出色的图像质量和性能表现吗&#xff1f;DLSS Swapper作为…

作者头像 李华
网站建设 2026/3/28 17:38:21

DLSS Swapper深度指南:解锁游戏画质与性能的终极秘籍

DLSS Swapper深度指南&#xff1a;解锁游戏画质与性能的终极秘籍 【免费下载链接】dlss-swapper 项目地址: https://gitcode.com/GitHub_Trending/dl/dlss-swapper 还在为游戏画面不够清晰流畅而烦恼吗&#xff1f;DLSS Swapper正是你需要的利器&#xff01;这款开源工…

作者头像 李华