跳转到内容

C++ 类与对象

来自代码酷

模板:Note

C++类与对象[编辑 | 编辑源代码]

类(Class)是C++面向对象编程的核心概念,它是用户自定义的数据类型,将数据(属性)和操作数据的函数(方法)封装在一起。对象(Object)则是类的具体实例。

基本概念[编辑 | 编辑源代码]

类定义[编辑 | 编辑源代码]

类通过class关键字定义,基本语法如下:

class ClassName {
    access_specifier:  // 访问修饰符(public/private/protected)
        member_variables;  // 成员变量
        member_functions();  // 成员函数
};

对象创建[编辑 | 编辑源代码]

创建类的对象有两种方式:

ClassName obj1;          // 栈上创建
ClassName* obj2 = new ClassName();  // 堆上创建(需手动释放内存)

详细说明[编辑 | 编辑源代码]

访问修饰符[编辑 | 编辑源代码]

C++提供三种访问控制:

  • public:类外可访问
  • private:仅类内可访问(默认)
  • protected:类及其子类可访问

classDiagram class BankAccount { -balance : double +deposit(amount: double) void +withdraw(amount: double) bool +getBalance() double }

成员函数[编辑 | 编辑源代码]

成员函数可在类内或类外定义。类外定义时需使用作用域解析运算符::

class Rectangle {
public:
    double width, height;
    double area();  // 声明
};

// 类外定义
double Rectangle::area() {
    return width * height;
}

构造函数与析构函数[编辑 | 编辑源代码]

  • 构造函数:对象创建时自动调用,通常用于初始化
  • 析构函数:对象销毁时自动调用,用于资源清理
class Student {
    string name;
    int age;
public:
    // 构造函数
    Student(string n, int a) : name(n), age(a) {}  // 初始化列表
    
    // 析构函数
    ~Student() {
        cout << "Student对象被销毁" << endl;
    }
};

完整示例[编辑 | 编辑源代码]

以下是一个银行账户类的实现:

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

class BankAccount {
private:
    string owner;
    double balance;

public:
    // 构造函数
    BankAccount(string o, double b) : owner(o), balance(b) {}

    // 存款
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "存款成功,当前余额: " << balance << endl;
        }
    }

    // 取款
    bool withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            cout << "取款成功,当前余额: " << balance << endl;
            return true;
        }
        cout << "取款失败,余额不足" << endl;
        return false;
    }

    // 查询余额
    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account("张三", 1000.0);
    account.deposit(500.0);    // 输出:存款成功,当前余额: 1500
    account.withdraw(200.0);   // 输出:取款成功,当前余额: 1300
    account.withdraw(2000.0);  // 输出:取款失败,余额不足
    
    cout << "最终余额: " << account.getBalance() << endl;  // 输出:最终余额: 1300
    return 0;
}

高级特性[编辑 | 编辑源代码]

this指针[编辑 | 编辑源代码]

this指针指向当前对象实例,常用于解决名称冲突:

class Example {
    int x;
public:
    void setX(int x) {
        this->x = x;  // 使用this区分成员变量和参数
    }
};

静态成员[编辑 | 编辑源代码]

静态成员属于类而非对象:

  • 静态变量:所有对象共享同一副本
  • 静态函数:只能访问静态成员
class Counter {
    static int count;  // 静态成员声明
public:
    Counter() { count++; }
    static int getCount() { return count; }
};

int Counter::count = 0;  // 静态成员定义

int main() {
    Counter c1, c2, c3;
    cout << "对象数量: " << Counter::getCount();  // 输出:3
}

友元[编辑 | 编辑源代码]

友元函数/类可以访问类的私有成员,破坏封装性,应谨慎使用:

class Box {
    double width;
public:
    friend void printWidth(Box box);  // 友元函数声明
};

void printWidth(Box box) {
    cout << "宽度: " << box.width;  // 访问私有成员
}

实际应用案例[编辑 | 编辑源代码]

游戏开发[编辑 | 编辑源代码]

在游戏开发中,类常用于表示游戏实体:

class Character {
    string name;
    int health;
    Vector2D position;
public:
    void move(Vector2D direction);
    void takeDamage(int amount);
    void heal(int amount);
};

GUI编程[编辑 | 编辑源代码]

GUI框架通常使用类表示窗口控件:

class Button {
    string text;
    Rect bounds;
    function<void()> onClick;
public:
    void draw();
    void handleClick();
};

最佳实践[编辑 | 编辑源代码]

1. 遵循单一职责原则:每个类只负责一个功能 2. 优先使用组合而非继承 3. 成员变量尽量设为private 4. 提供完整的构造函数,避免对象处于无效状态 5. 对于资源管理类,实现Rule of Three/Five(拷贝构造函数、拷贝赋值运算符、析构函数)

页面模块:Message box/ambox.css没有内容。

常见问题[编辑 | 编辑源代码]

类与结构体的区别[编辑 | 编辑源代码]

在C++中,classstruct的唯一区别是默认访问权限:

  • class默认private
  • struct默认public

何时使用堆对象[编辑 | 编辑源代码]

以下情况考虑使用堆对象(通过new创建):

  • 对象生命周期需要超出创建它的作用域
  • 对象很大,栈空间可能不足
  • 需要多态特性(通过基类指针操作派生类对象)

总结[编辑 | 编辑源代码]

类与对象是C++面向对象编程的基础,理解这些概念对后续学习继承、多态等高级特性至关重要。关键点包括:

  • 类定义数据和行为
  • 访问控制保护数据完整性
  • 构造函数/析构函数管理对象生命周期
  • 静态成员属于类而非对象
  • this指针引用当前对象

模板:Exercise