C++毎日練習(重荷)

1856 ワード

本文はブロガーのオリジナル文章であり、ブロガーの許可を得ずに転載してはならない.
https://blog.csdn.net/lxy_2011/article/details/52638634
一、今日の課題
1.関数のリロード
2.演算子のリロード
 
二、実戦演習
1.関数のリロード
  When two or more different declarations are specified for a single name in the same scope,  that name is said to overloaded.  By extension, two declarations in the same scope that declare the same name but with different types are called overloaded declarations. Only function declarations can be overloaded; object and type declarations cannot be overloaded. ——『ANSI C++Standard.P 290』より抜粋
1)何に使いますか.
関数名の数を減らしました.名前空間の汚染を避けた.プログラムの読み取り可能性を強化します.  
2)どう使いますか.
 
関数名に基づいて候補関数セットを決定候補関数セットから使用可能な関数セットを選択使用可能な関数セットから最適な関数を決定するか、あいまいなためエラーを返すことができます
 
2.演算子のリロード
演算子のリロードは、既存の演算子に多重の意味を与え、同じ演算子がドメインの異なるタイプのデータに異なる動作をもたらすようにします.
1)何に使いますか.
2つの複素数を作成し、「+」演算子で直接加算するとします.
1 Complex com1(10,10),com2(20,20),sum; 2 sum=com1+com2;
すると、これらのオペランドに一致する「+」演算子がないエラーが表示されます.これは、Complexクラスタイプが事前定義タイプではなく、システムがそのタイプのデータを加算演算子関数の再ロードする必要がないためです.C++は、演算子のリロードの方法、すなわち演算子のリロード関数を提供します.その関数名はoperatorの後にリロード演算子が続くように規定されています.たとえば、operator+()、operator*()などです.
2)どう使いますか. 
#include 

using namespace std;

class Complex
{
public:
    double real, imag;
    Complex(double real = 0, double imag = 0)
    {
        this->real = real;
        this->imag = imag;
    }
};

Complex operator +(Complex com1, Complex com2)
{
    return Complex(com1.real + com2.real, com1.imag + com2.imag);
}

int main()
{
    Complex com1(10, 10), com2(20, 20), sum;
    sum = com1 + com2;
    cout << "sum      :" << sum.real << endl;
    cout << "sum      :" << sum.imag << "i" << endl;

    system("pause");
    return 0;
}