はじめに
この実験では、C++ プログラミングにおけるコンストラクタとデストラクタの概念をどのように示すかを学びます。Rectangle と呼ばれるクラスを定義し、コンストラクタとデストラクタを使ってクラスオブジェクトを初期化および破棄するプログラムを開発します。
新しい C++ ソース ファイルを作成する
~/project ディレクトリに移動し、次のコマンドを使用して main.cpp と呼ばれる新しい C++ ソース ファイルを作成します。
touch main.cpp
Rectangle クラスを定義する
Rectangle と呼ばれるクラスを定義し、それに length と breadth の 2 つのパブリック属性を追加します。
#include <iostream>
using namespace std;
//Rectangle class to demonstrate the use of Constructor and Destructor in CPP
class Rectangle {
public:
float length, breadth;
//Declaration of the default Constructor of the Rectangle Class
public:
Rectangle() {
cout<<"Constructor Called"<<endl; //displaying the output when called
length = 2;
breadth = 4;
}
//Declaration of the Destructor of the Rectangle Class
public:
~Rectangle() {
cout<<"Destructor Called"<<endl; //displaying the output before destruct
}
};
クラス オブジェクトを作成する
Rectangle クラスのオブジェクトを作成します。これにより、オブジェクトを初期化するためのデフォルト コンストラクタが呼び出されます。
int main() {
Rectangle rect; //declaring an object of class Rectangle
return 0;
}
オブジェクトのプロパティを表示する
前の手順で作成したオブジェクトを使用して、Rectangle オブジェクトの長さと幅を表示します。
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++ プログラミングにおけるコンストラクタとデストラクタの概念をどのように示すかを学びました。Rectangle と呼ばれるクラスを定義し、デフォルト コンストラクタとデストラクタを使用してクラス オブジェクトを初期化および破棄しました。また、Rectangle オブジェクトのプロパティを表示しました。コンストラクタはクラスのオブジェクトが作成されたときに呼び出され、デストラクタはオブジェクトが破棄されたときに呼び出されました。



