返回

深入剖析C++:类、对象、继承与多态

闲谈

迈入C++面向对象世界的新篇章

在上一篇博客中,我们进行了C++之旅的开端,探索了C++与C语言的一些不同点。现在,我们将更深入地研究C++的面向对象编程(OOP)范式,探讨类、对象、继承和多态等基本概念。

第一幕:拉开类与对象的帷幕

类是C++中用于定义对象蓝图的数据结构。类包含对象属性(数据成员)和行为(方法)的成员变量和成员函数。对象是类的实例,可以拥有自己的数据和行为。

我们通过一个简单的例子来理解类与对象的概念:

class Person {
    string name;
    int age;

public:
    Person(string name, int age) {
        this->name = name;
        this->age = age;
    }

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

int main() {
    Person person1("John Doe", 25);
    Person person2("Jane Doe", 30);

    person1.printInfo();
    person2.printInfo();

    return 0;
}

在这个例子中,我们定义了一个名为Person的类,该类具有两个数据成员(nameage)和一个成员函数(printInfo)。然后,我们创建了两个Person对象(person1person2),并将它们的信息打印到控制台。

第二幕:揭开继承的神秘面纱

继承是OOP中最重要的概念之一。它允许类从另一个类(称为基类或父类)继承属性和行为。继承使我们能够创建具有相同或相似功能的新类,而无需重新编写代码。

class Student : public Person {
    int studentID;
    string major;

public:
    Student(string name, int age, int studentID, string major) : Person(name, age) {
        this->studentID = studentID;
        this->major = major;
    }

    void printInfo() {
        cout << "Name: " << name << ", Age: " << age << ", Student ID: " << studentID << ", Major: " << major << endl;
    }
};

int main() {
    Student student1("John Doe", 25, 123456, "Computer Science");
    Student student2("Jane Doe", 30, 234567, "Business Administration");

    student1.printInfo();
    student2.printInfo();

    return 0;
}

在上面的例子中,我们定义了一个名为Student的类,它从Person类继承属性和行为。Student类添加了两个新的数据成员(studentIDmajor)和一个新的成员函数(printInfo)。然后,我们创建了两个Student对象(student1student2),并将它们的信息打印到控制台。

第三幕:探索多态的变幻世界

多态性是OOP的另一个重要概念。它允许子类对象以不同的方式响应相同的函数调用。这使得我们可以编写能够处理不同类型对象的通用代码。

class Shape {
public:
    virtual void draw() = 0;  // Pure virtual function
};

class Rectangle : public Shape {
public:
    void draw() {
        cout << "Drawing a rectangle" << endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        cout << "Drawing a circle" << endl;
    }
};

int main() {
    Shape* shape1 = new Rectangle();
    Shape* shape2 = new Circle();

    shape1->draw();  // Output: Drawing a rectangle
    shape2->draw();  // Output: Drawing a circle

    return 0;
}

在这个例子中,我们定义了一个名为Shape的抽象类,它有一个纯虚函数drawRectangleCircle类从Shape类继承,并提供了draw函数的实现。然后,我们创建了两个Shape对象(shape1shape2),并调用它们的draw函数。由于多态性,这些函数调用以不同的方式响应,具体取决于对象的类型。

结语

类、对象、继承和多态是C++面向对象编程的基础。通过理解这些概念,我们可以编写出更健壮、更灵活和更可维护的代码。在下一篇文章中,我们将探讨C++中的一些高级面向对象特性,如抽象类、接口和泛型编程。