C++ 构造函数和析构函数示例程序

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何在 C++ 编程中演示构造函数(Constructor)和析构函数(Destructor)的概念。我们将开发一个程序来定义一个名为 Rectangle 的类,并利用构造函数和析构函数来初始化和销毁类对象。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/OOPGroup(["`OOP`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/OOPGroup -.-> cpp/classes_objects("`Classes/Objects`") cpp/OOPGroup -.-> cpp/access_specifiers("`Access Specifiers`") cpp/OOPGroup -.-> cpp/constructors("`Constructors`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/variables -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} cpp/classes_objects -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} cpp/access_specifiers -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} cpp/constructors -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} cpp/output -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} cpp/files -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} cpp/code_formatting -.-> lab-96126{{"`C++ 构造函数和析构函数示例程序`"}} end

创建一个新的 C++ 源文件

导航到 ~/project 目录,并使用以下命令创建一个名为 main.cpp 的 C++ 源文件:

touch main.cpp

定义 Rectangle 类

定义一个名为 Rectangle 的类,并为其添加两个公共属性 lengthbreadth

#include <iostream>

using namespace std;

//Rectangle 类用于演示 C++ 中构造函数和析构函数的使用
class Rectangle {
    public:
        float length, breadth;

    //声明 Rectangle 类的默认构造函数
    public:
        Rectangle() {
            cout<<"Constructor Called"<<endl;  //调用时显示输出
            length = 2;
            breadth = 4;
        }

    //声明 Rectangle 类的析构函数
    public:
        ~Rectangle() {
            cout<<"Destructor Called"<<endl;  //销毁前显示输出
        }
};

创建类对象

创建一个 Rectangle 类的对象。这将调用默认构造函数来初始化对象。

int main() {

    Rectangle rect;  //声明一个 Rectangle 类的对象

    return 0;
}

打印对象属性

使用上一步创建的对象打印 Rectangle 对象的 Length(长度)和 Breadth(宽度)。

int main() {

    cout<<"Length of the Rectangle: "<<rect.length<<endl;

    cout<<"Breadth of the Rectangle: "<<rect.breadth<<endl;

    return 0;
}

编译并运行程序

使用以下命令编译程序,并通过运行编译后的可执行文件来执行程序:

g++ main.cpp -o main && ./main

总结

在本实验中,我们学习了如何在 C++ 编程中演示构造函数(Constructor)和析构函数(Destructor)的概念。我们定义了一个名为 Rectangle 的类,并使用默认构造函数和析构函数来初始化和销毁类对象。我们还打印了 Rectangle 对象的属性。当创建类的对象时,构造函数被调用;而当对象被销毁时,析构函数被调用。

您可能感兴趣的其他 C++ 教程