C++(24)演算子のリロード

6858 ワード

コンセプト
重荷とは、新たな意味を与えることである.関数のリロードとは、既存の関数に新しい意味を与え、新しい機能を実現させることである.そのため、1つの関数名は異なる機能を表す関数、すなわち「1名多用」に使用することができる.
演算子を再ロードすることもできます.実際には、知らず知らずのうちに演算子の再ロードを使用しています.例えば、5+8、5.8+3.67などの整数、単精度数、二精度数を加算することに慣れていますが、コンピュータは整数、単精度数、二精度数の加算操作過程が異なりますが、C++は演算子「+」をリロードしているのでint、floatに適用できます.doubleタイプの演算.
「<>」もシフト演算子(右シフト)ですが、入力操作ではストリームオブジェクトcinと併用されるストリーム抽出演算子も使用されます.これが演算子リロード(operator overloading)です.C++システム対「<>」がリロードされ、ユーザーが異なる場合にそれらを使用する場合、役割は異なります.はい」<>「のリロード処理はヘッダファイルstreamに格納されます.したがって、プログラムで「<<"">」をストリーム挿入演算子およびストリーム抽出演算子として使用する場合は、ヘッダファイルstreamをこのファイルモジュールに含める必要があります(もちろん「using namespace std」も含む必要があります).
演算子の再ロード
1なぜ演算子リロードメカニズムで複数のクラスを使用するのか、例えばComplex c 3=c 1+c 2である.理由Complexはユーザーのカスタムタイプで、コンパイラはどのように加减コンパイラを行うか全然分からないメカニズムを提供して、ユーザーに自分で完成させて、カスタムタイプの加减操作...このメカニズムが演算子リロードメカニズム2演算子リロードの本質である関数
リロード演算子の制限
再ロードできない演算子(1).(2) : : (3) .* (4) ? : (5) sizeof
いくつかの原則(1)演算子の優先度を変更しない(2)演算子の結合性を変更しない(3)演算子を変更しないために必要なオペランド(4)新しい演算子を作成できない
#include 

using namespace std;

// 2 + 3i        
class Complex
{
    friend Complex add (const Complex &c1, const Complex &c2);
    friend Complex operator+(const Complex &c1, const Complex &c2);
    friend Complex operator+(const Complex &c1, int num);
public:
    Complex()
    {
        a = 0;
        b = 0;
    }

    Complex(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

    void print()
    {
        printf ("%d + %di
"
, a, b); } Complex add(const Complex &c2) { Complex tmp(a+c2.a, b+c2.b); return tmp; } Complex operator-(const Complex &c2) const { Complex tmp(a-c2.a, b-c2.b); return tmp; } private: int a; // int b; // }; Complex add(const Complex &c1, const Complex &c2) { Complex tmp(c1.a+c2.a, c1.b+c2.b); return tmp; } // // operator+ Complex operator+(const Complex &c1, const Complex &c2) { Complex tmp(c1.a+c2.a, c1.b+c2.b); return tmp; } Complex operator+(const Complex &c1, int num) { Complex tmp(c1.a + num, c1.b); return tmp; } // int main3_2() { Complex c1(1,2), c2(3,4), c; // c = c1 + c2; // c = operator+(c1, c2); // c = c1.add(c2); // // : c = c1.operator-(c2); c = c1 - c2; c.print(); return 0; } : 4 + 6i -2 + -2i int main3_1() { int a = 10, b = 20; int cc = a + b; // , Complex c1(1,2), c2(3,4), c; c1.print(); c2.print(); // Complex , c1, c2 , , // c = c1 + c2; // c = add(c1, c2); // c = operator+(c1, c2); // // // 1、 : operator + ( +:operator+, *: operator* []: operator[]) // 2、 , , :operator+(c1, c2); // 3、 :Complex operator+(const Complex &c1, const Complex &c2) c = c1 + c2; // c = operator+(c1, c2); // operator+ // operator+(c1, 10) ===> operator+(const Complex &c1, int num) // Complex operator+(const Complex &c1, int num) c = c1 + 10; c.print(); return 0; } : 1 + 2i 3 + 4i 11 + 2i