ゲームが作れるようになるまでがんばる日記

ゲーム制作のことを中心にゲームに関することを書いています

フレンド演算子関数

演算子オーバーロードをそのクラスのメンバ関数とせずにフレンド関数として定義することもできる。

#include <iostream>
using namespace std;

class Test {
private:
    int value;
public:
    Test() { value = 0; }
    Test(int n) { value = n; }
    
    friend Test operator+(Test a, Test b);
    
    void show() { cout << value << endl; }
};

Test operator+(Test a, Test b)
{
    Test temp;
    temp.value = a.value + b.value;
    return temp;
}

int main()
{
    Test x(123), y(456), z;

    z = x + y;
    z.show();

    return 0;
}

2項演算子の場合は二つの引数を取ることになる。そのため、演算子の左側、右側を別のものにすることができる。たとえば次のような感じ。

friend Test operator+(Test a, int n);
friend Test operator+(int n, Test a);

例:
Test x(123), y;
y = x + 456;
y = 456 + x;