パープルハット

※当サイトではGoogleアドセンス広告を利用しています

C++ クラス③(演算子の利用とcoutでの表示)





四則演算

friend関数を利用します。
以下では、2次元ベクトルクラス「Vector2」について、ベクトル同士の和と、スカラーとの積を計算できるようにしました。

#pragma once

#include <iostream>

//クラスの宣言
class Vector2 {
public:
    double x, y;

    //コンストラクタ
    Vector2(const double& _x = 0, const double& _y = 0) {
        x = _x;
        y = _y;
    }

    //(x, y)を表示する関数の処理
    void display() {
        std::cout << "(" << x << ", " << y << ")" << std::endl;
    }


    //加算用演算子
    friend Vector2 operator+(const Vector2& a, const Vector2& b);

    //スカラとの乗算
    friend Vector2 operator*(const double& a, const Vector2& b);
};


//スカラとの乗算
Vector2 operator+(const Vector2& a, const Vector2& b) {
    Vector2 c(0, 0);
    c.x = a.x + b.x;
    c.y = a.y + b.y;
    return c;
}


//スカラとの乗算
Vector2 operator*(const double& a, const Vector2& b) {
    Vector2 c(0, 0);
    c.x = a * b.x;
    c.y = a * b.y;
    return c;
}


呼び出し

#include "vector2.h"

int main() {

    Vector2 a(1, 3);
    Vector2 b(2, -1);

    Vector2 c = a + b;
    std::cout << "a + b = ";
    c.display();

    Vector2 d = 2.0 * a;
    std::cout << "2.0 * a = ";
    d.display();
}


実行結果

a + b = (3, 2)
2.0 * a = (2, 6)





複合演算子(+=とか)

friendとかなしに普通の関数の様に利用できます。
以下では、2次元ベクトルクラス「Vector2」について、+=の定義を行いました。

#pragma once

#include <iostream>

//クラスの宣言
class Vector2 {
public:
    double x, y;

    //コンストラクタ
    Vector2(const double& _x = 0, const double& _y = 0) {
        x = _x;
        y = _y;
    }

    //(x, y)を表示する関数の処理
    void display() {
        std::cout << "(" << x << ", " << y << ")" << std::endl;
    }


    //加算用演算子
    Vector2 operator+=(const Vector2& a);
};


//スカラとの乗算
Vector2 Vector2::operator+=(const Vector2& a) {
    x += a.x;
    y += a.y;
    return *this;
}


呼び出し

#include "vector2.h"

int main() {

    Vector2 a(1, 3);
    Vector2 b(2, -1);

    a += b;
    std::cout << "a = ";
    a.display();
}


実行結果

a = (3, 2)





std::coutでの表示

ベクトルの表示のために関数displayを使い、実際に表示する際は、

std::cout << "a = ";
a.display();

としてきましたが、毎回2行書くのは面倒です。

そこで、演算子を継承し、

friend std::ostream& operator << (std::ostream& os, const Vector2& v){
   os<<X;
}

とすると、std::coutしたときにXが表示されるようになります。

#pragma once

#include <iostream>

//クラスの宣言
class Vector2 {
public:
    double x, y;

    //コンストラクタ
    Vector2(const double& _x = 0, const double& _y = 0) {
        x = _x;
        y = _y;
    }

    friend std::ostream& operator << (std::ostream& os, const Vector2& v);
};

//std::coutでの表示
std::ostream& operator << (std::ostream& os, const Vector2& a) {
    os << "(" << a.x << ", " << a.y << ")";
    return os;
};


呼び出し

#include "vector2.h"

int main() {
    Vector2 a(1, 3);
    std::cout << "a = " << a << std::endl;
}


実行結果

a = (1, 3)