C++ 从入门到精通C++ 从入门到精通
首页
基础教程
进阶教程
实战项目
编程指南
首页
基础教程
进阶教程
实战项目
编程指南
  • 💪 进阶基础

    • 📚 C++ 进阶教程
    • 第8章 - 指针基础
    • 第9章 - 引用和动态内存
    • 第10章 - 结构体和枚举
    • 第11章 - 文件操作
    • 第12章 - 预处理器和命名空间
  • 🎯 面向对象编程

    • 第13章 - 类和对象基础
    • 第14章 - 构造函数和析构函数
    • 第15章 - 封装、继承、多态
    • 第16章 - 运算符重载
    • 第17章 - 模板基础
    • 第18章 - 异常处理
  • 📦 STL 标准模板库

    • 第19章 - Vector 和 String
    • 第20章 - 容器类
    • 第21章 - Map 和 Set
    • 第22章 - 算法和迭代器

第13章 - 类和对象基础

嗨,朋友!我是长安。

终于来到 C++ 最核心的部分——面向对象编程(OOP)!

之前我们用结构体来组织数据,但结构体只能存储数据。类(Class) 不仅能存储数据,还能定义操作这些数据的函数!

🎯 什么是类和对象?

生活中的例子

想象你要制作手机:

  • 类 = 手机设计图纸(定义手机有什么功能)
  • 对象 = 根据图纸生产出来的实际手机
// 设计图纸(类)
class Phone {
    // 属性:品牌、型号、价格
    // 功能:打电话、发短信、拍照
};

// 实际手机(对象)
Phone myPhone;     // 我的手机
Phone yourPhone;   // 你的手机

类 vs 结构体

特性结构体类
数据✅ 可以存储✅ 可以存储
函数✅ 可以有(C++)✅ 可以有
默认访问权限publicprivate
主要用途简单数据组合复杂对象建模

📝 定义和使用类

基本语法

class 类名 {
public:
    // 公有成员(外部可访问)
    数据成员;
    成员函数;
    
private:
    // 私有成员(外部不可访问)
    数据成员;
};

示例1:第一个类

#include <iostream>
#include <string>
using namespace std;

// 定义学生类
class Student {
public:
    // 数据成员(属性)
    int id;
    string name;
    double score;
    
    // 成员函数(方法)
    void display() {
        cout << "学号:" << id << endl;
        cout << "姓名:" << name << endl;
        cout << "成绩:" << score << endl;
    }
    
    void study() {
        cout << name << " 正在学习..." << endl;
    }
};

int main() {
    // 创建对象
    Student stu1;
    
    // 设置属性
    stu1.id = 1001;
    stu1.name = "张三";
    stu1.score = 95.5;
    
    // 调用方法
    stu1.display();
    stu1.study();
    
    return 0;
}

示例2:银行账户类

#include <iostream>
#include <string>
using namespace std;

class BankAccount {
public:
    string accountNumber;
    string ownerName;
    double balance;
    
    // 存款
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "存款成功!当前余额:" << balance << endl;
        } else {
            cout << "存款金额必须大于0!" << endl;
        }
    }
    
    // 取款
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "取款成功!当前余额:" << balance << endl;
        } else {
            cout << "余额不足或金额无效!" << endl;
        }
    }
    
    // 查询余额
    void checkBalance() {
        cout << "账户:" << accountNumber << endl;
        cout << "户主:" << ownerName << endl;
        cout << "余额:" << balance << " 元" << endl;
    }
};

int main() {
    BankAccount account;
    
    account.accountNumber = "6222001234567890";
    account.ownerName = "李四";
    account.balance = 1000.0;
    
    account.checkBalance();
    account.deposit(500);
    account.withdraw(300);
    account.checkBalance();
    
    return 0;
}

🔒 访问控制

public、private、protected

class MyClass {
public:
    int publicVar;        // 任何地方都可访问
    void publicFunc() {}
    
private:
    int privateVar;       // 只能在类内部访问
    void privateFunc() {}
    
protected:
    int protectedVar;     // 类内部和子类可访问
};

示例:封装数据

#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;
    
public:
    // Setter 方法
    void setName(string n) {
        name = n;
    }
    
    void setAge(int a) {
        if (a >= 0 && a <= 150) {
            age = a;
        } else {
            cout << "年龄无效!" << endl;
        }
    }
    
    // Getter 方法
    string getName() {
        return name;
    }
    
    int getAge() {
        return age;
    }
    
    void display() {
        cout << "姓名:" << name << ", 年龄:" << age << endl;
    }
};

int main() {
    Person p;
    
    p.setName("王五");
    p.setAge(25);
    
    p.display();
    
    // p.name = "xxx";  // ❌ 错误:私有成员不可访问
    
    return 0;
}

🔧 类内函数定义 vs 类外函数定义

类内定义(内联)

class Calculator {
public:
    int add(int a, int b) {
        return a + b;  // 直接在类内定义
    }
};

类外定义(推荐用于复杂函数)

class Calculator {
public:
    int add(int a, int b);      // 类内声明
    int subtract(int a, int b);
};

// 类外定义
int Calculator::add(int a, int b) {
    return a + b;
}

int Calculator::subtract(int a, int b) {
    return a - b;
}

🌟 实战案例

案例1:矩形类

#include <iostream>
using namespace std;

class Rectangle {
private:
    double length;
    double width;
    
public:
    void setDimensions(double l, double w) {
        length = l;
        width = w;
    }
    
    double getArea() {
        return length * width;
    }
    
    double getPerimeter() {
        return 2 * (length + width);
    }
    
    void display() {
        cout << "长:" << length << ", 宽:" << width << endl;
        cout << "面积:" << getArea() << endl;
        cout << "周长:" << getPerimeter() << endl;
    }
};

int main() {
    Rectangle rect;
    
    rect.setDimensions(10, 5);
    rect.display();
    
    return 0;
}

案例2:计数器类

#include <iostream>
using namespace std;

class Counter {
private:
    int count;
    
public:
    void setCount(int c) {
        count = c;
    }
    
    void increment() {
        count++;
    }
    
    void decrement() {
        count--;
    }
    
    void reset() {
        count = 0;
    }
    
    int getCount() {
        return count;
    }
    
    void display() {
        cout << "当前计数:" << count << endl;
    }
};

int main() {
    Counter c;
    
    c.setCount(10);
    c.display();
    
    c.increment();
    c.increment();
    c.display();
    
    c.decrement();
    c.display();
    
    c.reset();
    c.display();
    
    return 0;
}

案例3:时间类

#include <iostream>
using namespace std;

class Time {
private:
    int hour;
    int minute;
    int second;
    
public:
    void setTime(int h, int m, int s) {
        if (h >= 0 && h < 24 && m >= 0 && m < 60 && s >= 0 && s < 60) {
            hour = h;
            minute = m;
            second = s;
        } else {
            cout << "时间格式错误!" << endl;
        }
    }
    
    void display() {
        cout << (hour < 10 ? "0" : "") << hour << ":"
             << (minute < 10 ? "0" : "") << minute << ":"
             << (second < 10 ? "0" : "") << second << endl;
    }
    
    void addSecond() {
        second++;
        if (second >= 60) {
            second = 0;
            minute++;
            if (minute >= 60) {
                minute = 0;
                hour++;
                if (hour >= 24) {
                    hour = 0;
                }
            }
        }
    }
};

int main() {
    Time t;
    
    t.setTime(23, 59, 58);
    
    for (int i = 0; i < 5; i++) {
        t.display();
        t.addSecond();
    }
    
    return 0;
}

输出:

23:59:58
23:59:59
00:00:00
00:00:01
00:00:02

案例4:图书类

#include <iostream>
#include <string>
using namespace std;

class Book {
private:
    string title;
    string author;
    double price;
    int pages;
    
public:
    void setInfo(string t, string a, double p, int pg) {
        title = t;
        author = a;
        price = p;
        pages = pg;
    }
    
    void display() {
        cout << "书名:" << title << endl;
        cout << "作者:" << author << endl;
        cout << "价格:¥" << price << endl;
        cout << "页数:" << pages << endl;
    }
    
    void applyDiscount(double percent) {
        price *= (1 - percent / 100);
        cout << "折扣后价格:¥" << price << endl;
    }
};

int main() {
    Book book;
    
    book.setInfo("C++ Primer", "Stanley B. Lippman", 128.00, 950);
    book.display();
    
    cout << "\n应用8折优惠..." << endl;
    book.applyDiscount(20);
    
    return 0;
}

🎯 小结

概念说明示例
类对象的蓝图class Student { };
对象类的实例Student stu;
成员变量对象的属性int age;
成员函数对象的方法void display();
public公有访问外部可访问
private私有访问只能类内访问
封装隐藏内部实现用private保护数据

面向对象三大特性:

  1. 封装 - 将数据和操作封装在一起,隐藏实现细节
  2. 继承 - 下一章学习
  3. 多态 - 后续章节学习

💪 练习题

  1. 创建一个圆形类,包含半径属性和计算面积、周长的方法
  2. 创建一个学生类,包含姓名、成绩,添加判断是否及格的方法
  3. 创建一个温度类,实现摄氏度和华氏度的转换
  4. 创建一个点类(Point),包含x、y坐标,计算到原点的距离
  5. 创建一个商品类,实现库存管理(增加库存、减少库存)

🚀 下一步

太棒了!你已经掌握了类和对象的基础!

下一章,我们要学习构造函数和析构函数,让对象的创建和销毁更加优雅!

➡️ 第14章 - 构造函数和析构函数

最近更新: 2025/12/26 17:25
Contributors: 王长安
Next
第14章 - 构造函数和析构函数