C++ 类与对象详解
                           
天天向上
发布: 2025-03-29 15:14:25

原创
316 人浏览过

在 C++ 中,类(Class)是面向对象编程(OOP)的一部分,是一种用户自定义的数据类型,用于封装数据和相关操作。类将数据和操作数据的函数(称为方法)绑定在一起,从而实现数据抽象和封装。对象是类的实例,通过类来创建对象。

1. 类的基本概念

  • 类 (Class):类是数据和函数的集合,用来描述一类对象的属性和行为。
  • 对象 (Object):对象是类的实例。可以通过类来创建对象,每个对象都有自己的数据成员和方法。

2. 类的定义

类的定义包括:

  • 类名:类的标识符,用于引用类。
  • 成员变量:类中的变量,用来存储数据。
  • 成员函数:类中的函数,定义对象的行为。

类的基本结构:

class ClassName {
    public:    // 访问修饰符
        // 构造函数
        ClassName();  
        // 成员函数
        void memberFunction();  
    private:
        // 数据成员
        int data;
};

3. 类的构造函数与析构函数

  • 构造函数 (Constructor):用于创建对象并初始化对象的成员变量。构造函数的名称与类名相同。
  • 析构函数 (Destructor):用于销毁对象时释放资源,析构函数的名称与类名相同,但前面加上 ~

示例:

#include <iostream>
using namespace std;

class Car {
public:
    // 构造函数
    Car(string model, int year) {
        this->model = model;
        this->year = year;
        cout << "Car object created: " << model << " " << year << endl;
    }

    // 析构函数
    ~Car() {
        cout << "Car object destroyed: " << model << " " << year << endl;
    }

    // 成员函数
    void display() {
        cout << "Model: " << model << ", Year: " << year << endl;
    }

private:
    string model;
    int year;
};

int main() {
    Car car1("Tesla", 2020);  // 创建对象
    car1.display();

    // 在函数结束时自动调用析构函数,销毁 car1 对象
    return 0;
}

输出:

Car object created: Tesla 2020
Model: Tesla, Year: 2020
Car object destroyed: Tesla 2020

4. 类的成员函数

类的成员函数用于操作类中的数据成员。成员函数可以定义为:

  • 普通成员函数:作用于对象。
  • 静态成员函数:与类相关,而不是与某个对象实例相关。

普通成员函数:普通成员函数需要通过对象来调用。

示例:

class Rectangle {
public:
    void setDimensions(int l, int b) {
        length = l;
        breadth = b;
    }

    int area() {
        return length * breadth;
    }

private:
    int length;
    int breadth;
};

int main() {
    Rectangle rect;
    rect.setDimensions(10, 5);
    cout << "Area of rectangle: " << rect.area() << endl;
    return 0;
}

静态成员函数:静态成员函数属于类本身,而不是某个对象实例,可以通过类名直接调用。

示例:

class Counter {
public:
    static int count;

    Counter() {
        count++;
    }

    static void showCount() {
        cout << "Count: " << count << endl;
    }
};

int Counter::count = 0;

int main() {
    Counter::showCount(); // 调用静态成员函数

    Counter c1, c2;
    Counter::showCount(); // 调用静态成员函数

    return 0;
}

输出:

Count: 0
Count: 2

5. 对象的创建与销毁

  • 创建对象:通过类的构造函数来创建对象。
  • 销毁对象:当对象的作用域结束时,析构函数会自动调用。

示例:

class Box {
public:
    Box(int l, int b, int h) : length(l), breadth(b), height(h) {}

    int volume() {
        return length * breadth * height;
    }

private:
    int length;
    int breadth;
    int height;
};

int main() {
    Box box1(3, 4, 5);  // 创建对象
    cout << "Volume of box1: " << box1.volume() << endl;

    return 0;
}

6. 访问控制

C++ 类中的成员可以有不同的访问权限,这由访问修饰符决定:

  • public:公有成员,类外部可以访问。
  • private:私有成员,类外部不可访问。
  • protected:保护成员,子类可以访问。

示例:

class Student {
public:
    string name;
    int age;

    void setDetails(string n, int a) {
        name = n;
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Student s1;
    s1.setDetails("John", 21);
    s1.display();
    return 0;
}

7. 类的继承 (Inheritance)

C++ 支持继承机制,允许创建一个类(子类)从另一个类(基类)继承成员。这使得可以重用已有类的功能,并通过继承添加或修改功能。

示例:

class Animal {
public:
    void speak() {
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {  // Dog 继承 Animal 类
public:
    void speak() {
        cout << "Dog barks" << endl;
    }
};

int main() {
    Dog dog;
    dog.speak();  // 调用重写的函数
    return 0;
}

8. 多态 (Polymorphism)

多态是面向对象编程的特性,允许使用相同的接口调用不同类型的对象行为。C++ 支持两种多态:

  • 静态多态(编译时多态):函数重载、运算符重载。
  • 动态多态(运行时多态):基类指针调用派生类重写的函数,通常与虚函数结合使用。

示例:

class Base {
public:
    virtual void show() {  // 虚函数
        cout << "Base class" << endl;
    }
};

class Derived : public Base {
public:
    void show() override {  // 重写基类的 show 方法
        cout << "Derived class" << endl;
    }
};

int main() {
    Base* basePtr;
    Derived derivedObj;
    basePtr = &derivedObj;

    basePtr->show();  // 动态绑定,调用 Derived 类的方法
    return 0;
}

9. 运算符重载 (Operator Overloading)

C++ 允许对内置运算符进行重载,使其适用于用户定义的类。通过运算符重载,可以让对象使用自定义的运算符。

示例:

class Complex {
public:
    int real, imag;

    Complex operator + (Complex const &other) {
        Complex temp;
        temp.real = real + other.real;
        temp.imag = imag + other.imag;
        return temp;
    }
};

int main() {
    Complex c1, c2, c3;
    c1.real = 10; c1.imag = 5;
    c2.real = 20; c2.imag = 15;
    c3 = c1 + c2;  // 使用重载的加法运算符

    cout << "Sum: " << c3.real << " + " << c3.imag << "i" << endl;
    return 0;
}

总结

  • 类和对象是面向对象编程的核心,通过类封装数据和方法,并通过对象实现具体的功能。
  • 构造函数与析构函数负责对象的创建与销毁。
  • 继承与多态允许扩展和重用已有类的功能,支持灵活的动态行为。
  • 运算符重载可以让对象使用常规的运算符进行操作。

C++ 的类与对象是强大且灵活的编程工具,它们支持数据封装、继承、重用、动态行为和代码可读性。掌握这些概念对深入学习 C++ 至关重要。

发表回复 0

Your email address will not be published. Required fields are marked *