🏗️ C++ 类和对象 - L28 进阶概念

掌握面向对象编程:类的定义、封装、构造函数和析构函数

📚 面向对象编程概述

什么是面向对象?

面向对象编程(OOP)是一种编程范式,它将数据和操作数据的方法封装在一起,形成类(Class),通过创建对象(Object)来使用。

  • 封装:将数据和行为包装在一起
  • 抽象:隐藏复杂实现,暴露简单接口
  • 继承:子类可以继承父类的特性
  • 多态:同一接口,不同实现
💡 类和对象的关系:
是蓝图/模板(如:汽车设计图)
对象是实例(如:具体的某辆汽车)
• 一个类可以创建多个对象

类的定义

#include <iostream> #include <string> using namespace std; // 定义一个Student类 class Student { public: // 成员变量(属性) string name; int age; double score; // 成员函数(方法) void introduce() { cout << "我叫" << name << ",今年" << age << "岁,成绩" << score << endl; } void study(int hours) { cout << name << "学习了" << hours << "小时" << endl; score += hours * 0.5; // 学习提高成绩 } }; int main() { // 创建对象 Student stu1; stu1.name = "张三"; stu1.age = 18; stu1.score = 85.5; // 调用方法 stu1.introduce(); stu1.study(2); stu1.introduce(); return 0; }

访问控制修饰符

class Student { public: // 公有成员:任何地方都可以访问 string name; void introduce(); private: // 私有成员:只能在类内部访问 double score; void calculateGrade(); protected: // 保护成员:类和子类可以访问 int studentId; };
💡 访问控制规则:
public:公开,任何地方都可访问
private:私有,只有类内部可访问(默认)
protected:保护,类和子类可访问
• 良好的封装:数据private,接口public

⚙️ 构造函数和析构函数

构造函数

#include <iostream> #include <string> using namespace std; class Student { public: string name; int age; // 默认构造函数 Student() { name = "未知"; age = 0; cout << "默认构造函数被调用" << endl; } // 带参数的构造函数 Student(string n, int a) { name = n; age = a; cout << "参数构造函数被调用:" << name << endl; } void introduce() { cout << name << ", " << age << "岁" << endl; } }; int main() { // 使用默认构造函数 Student stu1; stu1.introduce(); // 使用参数构造函数 Student stu2("李四", 19); stu2.introduce(); return 0; }

析构函数

#include <iostream> using namespace std; class Resource { public: string resourceName; Resource(string name) { resourceName = name; cout << "创建资源:" << resourceName << endl; } // 析构函数:对象销毁时自动调用 ~Resource() { cout << "释放资源:" << resourceName << endl; } }; int main() { { Resource res1("文件1"); Resource res2("文件2"); // res1和res2在这里使用 } // 离开作用域,析构函数自动调用 cout << "程序继续执行..." << endl; return 0; }

初始化列表

#include <iostream> #include <string> using namespace std; class Student { private: string name; int age; const int id; // const成员必须在初始化列表中初始化 public: // 使用初始化列表 Student(string n, int a, int i) : name(n), age(a), id(i) { // 初始化列表 cout << "学生创建:" << name << endl; } void show() { cout << "ID: " << id << ", 姓名: " << name << ", 年龄: " << age << endl; } }; int main() { Student stu("王五", 20, 1001); stu.show(); return 0; }
🎮 互动实验:类的使用演示

输入学生信息,观察对象的创建和使用

输入信息后点击按钮...

🛠️ 封装和数据隐藏

Getter和Setter方法

#include <iostream> #include <string> using namespace std; class Student { private: string name; int age; double score; public: // Getter方法:获取私有成员的值 string getName() { return name; } int getAge() { return age; } double getScore() { return score; } // Setter方法:设置私有成员的值(带验证) void setName(string n) { name = n; } void setAge(int a) { if (a >= 0 && a <= 150) { age = a; } else { cout << "年龄无效!" << endl; } } void setScore(double s) { if (s >= 0 && s <= 100) { score = s; } else { cout << "成绩无效!" << endl; } } void show() { cout << name << ", " << age << "岁, 成绩: " << score << endl; } }; int main() { Student stu; stu.setName("李四"); stu.setAge(19); stu.setScore(92.5); stu.show(); return 0; }

this指针

#include <iostream> #include <string> using namespace std; class Student { private: string name; int age; public: // this指针指向当前对象 void setData(string name, int age) { this->name = name; // this->name区分成员变量和参数 this->age = age; } // 返回当前对象的引用(支持链式调用) Student& setName(string n) { name = n; return *this; } Student& setAge(int a) { age = a; return *this; } void show() { cout << name << ", " << age << "岁" << endl; } }; int main() { Student stu; // 链式调用 stu.setName("王五").setAge(20); stu.show(); return 0; }

静态成员

#include <iostream> using namespace std; class Counter { private: static int count; // 静态成员变量(所有对象共享) public: Counter() { count++; // 每创建一个对象,计数+1 } static int getCount() { // 静态成员函数 return count; } ~Counter() { count--; // 销毁一个对象,计数-1 } }; // 初始化静态成员变量 int Counter::count = 0; int main() { cout << "初始计数:" << Counter::getCount() << endl; // 0 Counter c1, c2, c3; cout << "创建3个对象后:" << Counter::getCount() << endl; // 3 return 0; } // 离开作用域,对象销毁,count变为0

🚀 实际应用示例

完整的银行账户类

#include <iostream> #include <string> using namespace std; class BankAccount { private: string accountHolder; string accountNumber; double balance; public: // 构造函数 BankAccount(string holder, string number, double initialBalance = 0) : accountHolder(holder), accountNumber(number), balance(initialBalance) { cout << "账户创建:" << accountHolder << endl; } // 存款 void deposit(double amount) { if (amount > 0) { balance += amount; cout << "存款 " << amount << " 成功,余额:" << balance << endl; } } // 取款 bool withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; cout << "取款 " << amount << " 成功,余额:" << balance << endl; return true; } cout << "取款失败!" << endl; return false; } // 查询余额 double getBalance() { return balance; } // 显示账户信息 void showInfo() { cout << "=== 账户信息 ===" << endl; cout << "户名:" << accountHolder << endl; cout << "账号:" << accountNumber << endl; cout << "余额:" << balance << endl; } // 析构函数 ~BankAccount() { cout << "账户关闭:" << accountHolder << endl; } }; int main() { BankAccount account("张三", "123456789", 1000); account.showInfo(); account.deposit(500); account.withdraw(200); account.showInfo(); return 0; }

对象数组

#include <iostream> #include <string> using namespace std; class Student { private: string name; double score; public: Student(string n = "", double s = 0) : name(n), score(s) {} string getName() { return name; } double getScore() { return score; } void show() { cout << name << ": " << score << endl; } }; int main() { // 创建对象数组 Student students[3] = { Student("张三", 90), Student("李四", 85), Student("王五", 92) }; // 遍历对象数组 double total = 0; for (int i = 0; i < 3; i++) { students[i].show(); total += students[i].getScore(); } cout << "平均分:" << total / 3 << endl; return 0; }

📝 实战练习

📝 理解测试

以下代码中,构造函数的调用顺序是什么?

#include <iostream> using namespace std; class A { public: A() { cout << "A"; } ~A() { cout << "a"; } }; class B { public: B() { cout << "B"; } ~B() { cout << "b"; } }; int main() { A a; B b; return 0; }
选择答案查看解析...
💻 综合挑战

题目:设计一个Rectangle(矩形)类:
1. 私有成员:width(宽)、height(高)
2. 构造函数:支持默认值和无参构造
3. 方法:计算面积、计算周长、显示信息
4. 使用getter/setter访问私有成员
5. 创建多个矩形对象并比较面积

点击"生成代码框架"查看提示...