C++ クラスのメンバ関数のオーバーロードのサンプル
書式
class クラス名
データの型 関数名(データの型 引数1){処理コード}
データの型 関数名(データの型 引数1,データの型 引数2){処理コード}
クラスの同じメンバ関数名です。違いは引数の数が異なっています。
関数名またはクラスのメンバ関数名またはコンストラクタ名が同じで引数の型や数が異なるものです。
渡す引数によって自動的に引数にあった関数またはメンバ関数またはコンストラクタが実行されます。
使用例
#include <iostream>
using namespace std;
class City
{
public:
void print1(string str1) // メンバ関数
{
cout << str1 << "\n";
};
public:
void print1(string str1, string str2) // メンバ関数
{
cout << str1 << " and " << str2 << "\n";
};
};
int main()
{
City *cft = new City;
cft->print1("東京");
cft->print1("東京", "大阪");
}
#include <iostream>
using namespace std;
class City
{
public:
void print1(string str1) // メンバ関数
{
cout << str1 << "\n";
};
public:
void print1(string str1, string str2) // メンバ関数
{
cout << str1 << " and " << str2 << "\n";
};
};
int main()
{
City *cft = new City;
cft->print1("東京");
cft->print1("東京", "大阪");
}
#include <iostream> using namespace std; class City { public: void print1(string str1) // メンバ関数 { cout << str1 << "\n"; }; public: void print1(string str1, string str2) // メンバ関数 { cout << str1 << " and " << str2 << "\n"; }; }; int main() { City *cft = new City; cft->print1("東京"); cft->print1("東京", "大阪"); }
実行結果
東京
東京 and 大阪