function overloading, operator overloading


関数の再ロード
関数名が同じでパラメータが異なる場合
(ex. func(1), func("hi"))
name manglingを使用してコンパイラを異なる関数にする
もう一つの説は静的多態性と呼ばれる.
コンパイル時間に依存して、どの関数がバインドされるか
反対の概念には動的多態性がある.
これは、ランタイムがどの関数がバインドされるかを決定するためです.
これはvirtualキーワードによって生成されます.
前に、関数のリロードをfree関数として実装します.
class内部のmember関数も実現できる.

operator overloading
*、%、/、new、delete、[]、()など.
複数の例で説明します.
#include <iostream>
using namespace std;
struct complexNum {
	double real;
    double imag;
    
    complexNum(double r, double i): real{r}, imag{i} {};
    void print() const {
    	cout << real << " " << imag << "i" << endl;
    }
};

int main() {
	complexNum c1{1, 1};
    complexNum c2{1, 2};
    complexNum c{c1 + c2};
    c.print();
}
直接構築するとエラーが発生します.
complexNum c{c1 + c2};定義された演算子「+」がないためです.
#include <iostream>
using namespace std;
struct complexNum {
	double real;
    double imag;
    
    complexNum(double r, double i): real{r}, imag{i} {};
    void print() const {
    	cout << real << " " << imag << "i" << endl;
    }
};

complexNum operator+(const complexNum& lhs, const complexNum& rhs) {
	complexNum c{lhs.real+rhs.real, lhs.imag+rhs.imag}
    return 0;
}

int main() {
	complexNum c1{1, 1};
    complexNum c2{1, 2};
    complexNum c{c1 + c2};
    c.print();
}
以上のように、オペレータ+で「+」を定義できます.
#include <iostream>
#include <string>

class Cat
{
public:
	Cat(std::string name,int age): mName{std::move(name)},mAge{age} {};
	const std::string& name() const
	{
		return mName;
	};
	int age() const
	{
		return mAge;
	};
	// void print(std::ostream& os) const
	// {
	// 	os << mName << " " << mAge << std::endl;
	// };

private:
	std::string mName;
	int mAge;
};

std::ostream& operator<<(std::ostream& os, const Cat& c)
{
	return os<< c.name() <<" " << c.age();
};



int main()
{
	Cat kitty{"kitty",1};
	Cat nabi{"nabi", 2};

	std::cout << kitty << std::endl;
	std::cout << nabi << std::endl;
	// ==, < , <<

	// kitty.print(std::cout);
	// nabi.print(std::cout);
	return 0;

}
std::ostream& operator<<(std::ostream& os, const Cat& c)
{
return os<< c.name() <<""<< c.age();
};
coutはostreamの種類の一つであることがわかります.
std::ostream& operator<<(std::ostream& os, const Cat& c)
{
return os<< c.name() <<""<< c.age();
};
出力ストリームの作成と作成に使用する<<<オペレータ.std::cout << kitty << std::endl;
に出力します.
OOPを中心とした直感的な出力をサポートするoutputstreamを受け入れる柔軟な関数です.