はじめに
この実験では、C++ プログラミング言語におけるメソッドのオーバーロードの概念をどのように示すかを学びます。メソッドのオーバーロードは、クラス内に同じ名前の複数のメソッドまたは関数を持つことができる概念ですが、パラメータは異なります。メソッド呼び出し時に渡されるパラメータの数と型に基づいて、適切なメソッドが呼び出されます。
この実験では、C++ プログラミング言語におけるメソッドのオーバーロードの概念をどのように示すかを学びます。メソッドのオーバーロードは、クラス内に同じ名前の複数のメソッドまたは関数を持つことができる概念ですが、パラメータは異なります。メソッド呼び出し時に渡されるパラメータの数と型に基づいて、適切なメソッドが呼び出されます。
まず、次のコマンドを使用して ~/project
ディレクトリに新しい C++ ファイル main.cpp
を作成します。
touch ~/project/main.cpp
shape
という名前のクラスを作成し、パラメータの数が異なる area()
という名前の 2 つのメソッドを定義します。input()
メソッドは、ユーザーから入力を受け取り、メンバ変数 l
、b
、および s
の値を設定します。その後、main()
メソッドを定義して、クラスの外部から shape
クラスのメンバにアクセスします。
#include <iostream>
using namespace std;
class shape {
//メンバ変数を宣言する
public:
int l, b, s;
//メンバ関数またはメソッドを定義する
public:
void input() {
cout << "Enter the length of each side of the Square: \n";
cin >> s;
cout << "\n";
cout << "Enter the length and breadth of the Rectangle: \n";
cin >> l >> b;
cout << "\n";
}
//メソッドのオーバーロードを示す
public:
void area(int side) {
cout << "Area of Square = " << side * side << endl;
}
void area(int length, int breadth) {
cout << "Area of Rectangle = " << length * breadth << endl;
}
};
int main() {
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate Method Overloading in a Class, in CPP ===== \n\n";
//クラスの外部からクラスのメンバにアクセスするためのクラスオブジェクトを宣言する
shape sh;
cout << "\nCalling the input() function to take the values from the user\n";
sh.input();
cout << "\nCalling the area(int) function to calculate the area of the Square\n";
sh.area(sh.s);
cout << "\nCalling the area(int,int) function to calculate the area of the Rectangle\n";
sh.area(sh.l, sh.b);
cout << "\nExiting the main() method\n\n\n";
return 0;
}
次に、以下のコマンドを使用してコードをコンパイルして実行します。
g++ main.cpp -o main && ./main
プログラムの出力は以下の通りになります。
Welcome to LabEx :-)
===== Program to demonstrate Method Overloading in a Class, in CPP =====
Calling the input() function to take the values from the user
Enter the length of each side of the Square:
4
Enter the length and breadth of the Rectangle:
5
6
Calling the area(int) function to calculate the area of the Square
Area of Square = 16
Calling the area(int,int) function to calculate the area of the Rectangle
Area of Rectangle = 30
Exiting the main() method
ここでは、ユーザー入力を受け取るために input()
メソッドが呼び出されていることがわかります。その後、1 つのパラメータを持つ area()
メソッドが呼び出されて正方形の面積が計算され、2 つのパラメータを持つ area()
メソッドが呼び出されて長方形の面積が計算されます。
この実験では、C++ プログラミング言語におけるメソッドのオーバーロードの概念をどのように使用するかを学びました。異なる数のパラメータを持つ 2 つの area()
という名前のメソッドを持つ shape
という名前のクラスを定義するプログラムを作成しました。これらのメソッドはオーバーロードされています。ユーザーは長方形の長さと幅と正方形の一辺の長さを入力します。そして、オーバーロードされたメソッドを使用して両方の形状の面積を計算します。