当前位置: 首页 > ai >正文

C++面向对象编程:类与对象详解

C++面向对象编程:类与对象详解

引言

面向对象编程(OOP)是现代编程的核心范式之一,它通过"对象"的概念来组织代码和数据。在C++中,类和对象是实现OOP的基础构建块。本文将全面讲解C++中类与对象的概念、语法和实际应用,帮助您建立坚实的面向对象编程基础。

从结构体到类

在C++中,类可以看作是结构体的扩展。两者关键区别在于默认访问权限:

// 结构体示例
struct Student {std::string name;  // 默认publicint age;float gpa;
};// 类示例
class Student {std::string name;  // 默认privateint age;float gpa;
};

类的基本概念

类的定义

class Rectangle {
private:double width, height;  // 私有成员public:// 构造函数Rectangle(double w, double h) : width(w), height(h) {}// 成员函数double area() const {return width * height;}// 访问器double getWidth() const { return width; }void setWidth(double w) { if(w > 0) width = w; }
};

访问修饰符

  • private: 仅类内可访问
  • protected: 类内和派生类可访问
  • public: 完全公开访问

对象的创建与使用

Rectangle rect(5.0, 3.0);  // 栈上创建
double a = rect.area();    // 调用成员函数// 动态创建
Rectangle* pRect = new Rectangle(4.0, 2.0);
delete pRect;  // 记得释放内存

类成员详解

成员变量

class Counter {
private:int count;            // 实例变量static int total;     // 静态变量const int MAX = 100;  // const成员public:Counter() : count(0) { total++; }
};int Counter::total = 0;  // 静态成员初始化

成员函数

class Circle {
private:double radius;public:// 类内定义double area() const { return 3.14159 * radius * radius; }// 类外定义void setRadius(double r);
};void Circle::setRadius(double r) {radius = r;
}

特殊成员函数

class Person {
private:std::string name;int age;public:// 构造函数Person(const std::string& n, int a) : name(n), age(a) {}// 析构函数~Person() { /* 清理资源 */ }// 拷贝构造函数Person(const Person& other) : name(other.name), age(other.age) {}
};

类的关系

组合关系

class Engine {
public:void start() { /*...*/ }
};class Car {
private:Engine engine;  // 组合
};

关联关系

class Student;class Course {
private:std::vector<Student*> students;  // 关联
};

银行账户系统示例

class BankAccount {
private:std::string accountNumber;double balance;std::vector<Transaction> history;  // 组合public:BankAccount(const std::string& accNum) : accountNumber(accNum), balance(0) {}void deposit(double amount) {balance += amount;recordTransaction("Deposit", amount);}// 其他成员函数...
};

最佳实践

  1. 封装原则:隐藏实现细节,提供清晰接口
  2. 合理初始化:使用初始化列表,确保所有成员初始化
  3. const正确性:适当使用const修饰符
  4. 避免过大类:遵循单一职责原则
  5. 谨慎使用友元:仅在必要时破坏封装

总结

类和对象是C++面向对象编程的基础,提供了封装、代码重用和模块化等优势。掌握这些概念对于编写可维护的C++代码至关重要。下一篇文章将深入探讨继承和多态性,进一步扩展面向对象编程的能力。

http://www.xdnf.cn/news/10572.html

相关文章:

  • CppCon 2014 学习:(Costless)Software Abstractions for Parallel Architectures
  • 已有的前端项目打包到tauri运行(windows)
  • Python应用range函数初解pro
  • arc3.2语言sort的时候报错:(sort < `(2 9 3 7 5 1)) 需要写成这种:(sort > (pair (list 3 2)))
  • EXCEL--累加,获取大于某个值的第一个数
  • DeepSeek模型高级应用:提示工程与Few-shot学习实战指南
  • 【深度学习-Day 21】框架入门:神经网络模型构建核心指南 (Keras PyTorch)
  • MySQL中的字符串分割函数
  • Python 训练营打卡 Day 33-神经网络
  • tex中的表格4:自动表格宽度自动换行tabularx宏包
  • 结构化控制语言(SCL) 与梯形图(LAD)相互转换的步骤指南
  • CppCon 2014 学习:EFFICIENCY PERFORMANCE ALGORITHMS DATA STRUCTURES
  • Linux中的System V通信标准-共享内存、消息队列以及信号量
  • 工作流引擎-18-开源审批流项目之 plumdo-work 工作流,表单,报表结合的多模块系统
  • isp中的 ISO代表什么意思
  • 【机器学习基础】机器学习入门核心算法:多分类与多标签分类算法
  • Vue3(watch,watchEffect,标签中ref的使用,TS,props,生命周期)
  • vue · 路由传参query和params
  • 50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Sound Board(音响控制面板)
  • 【Linux网络】传输层TCP协议
  • Sxer.Base.Debug(打印调试)
  • 腾答知识竞赛系统功能介绍
  • 【Java】泛型
  • 线性代数复习
  • Bootstrap 5学习教程,从入门到精通,Bootstrap 5 安装及使用(2)
  • CNN卷积网络:让计算机拥有“火眼金睛“(superior哥AI系列第4期)
  • Linux——计算机网络基础
  • 分布式锁剖析
  • 微软markitdown PDF/WORD/HTML文档转Markdown格式软件整合包下载
  • React Hooks 与异步数据管理