C++ 연산자 오버로딩 - 비트 연산자 오버로딩

진경천·2023년 9월 26일
0

C++

목록 보기
47/90

cout, cin 구현

	friend ostream& operator<<(ostream& os, const Vector& v) {
		os << v.x << " " << v.y << " " << v.z;
		return os;
	}

	friend istream& operator>>(istream& is, Vector& v) {
		string temp;
		is >> temp;
		v.x = stoi(temp);

		is >> temp;
		v.y = stoi(temp);

		is >> temp;
		v.z = stoi(temp);

		return is;
	}   

비트연산 구현

	Vector operator~() const {
		return Vector(~x, ~y, ~z);
	}

	Vector operator&(const Vector& v) const {
		return Vector{ x & v.x, y & v.y, z & v.z };
	}
	
	Vector operator|(const Vector& v) const {
		return Vector{ x | v.x, y | v.y, z | v.z };
	}

	Vector operator^(const Vector& v) const {
		return Vector{ x ^ v.x, y ^ v.y, z ^ v.z };
	}

	Vector operator<<(int shift) const {
		return Vector{ x << shift, y << shift, z << shift };
	}

	Vector operator>>(int shift) const {
		return Vector{ x >> shift, y >> shift, z >> shift };
	}

예제

#include <iostream>
#include <string>

using namespace std;

class Vector {
private:
	int x;
	int y;
	int z;

public:
	Vector(int x, int y, int z)
		: x(x), y(y), z(z) {
	}
	Vector() {

	}

	friend ostream& operator<<(ostream& os, const Vector& v) {
    // ostream 클래스를 friend로 가져옴
		os << v.x << " " << v.y << " " << v.z;
		return os;
	}

	friend istream& operator>>(istream& is, Vector& v) {
		string temp;
		is >> temp;
		v.x = stoi(temp);

		is >> temp;
		v.y = stoi(temp);

		is >> temp;
		v.z = stoi(temp);

		return is;
	}

	Vector operator~() const {
		return Vector(~x, ~y, ~z);
	}

	Vector operator&(const Vector& v) const {
		return Vector{ x & v.x, y & v.y, z & v.z };
	}
	
	Vector operator|(const Vector& v) const {
		return Vector{ x | v.x, y | v.y, z | v.z };
	}

	Vector operator^(const Vector& v) const {
		return Vector{ x ^ v.x, y ^ v.y, z ^ v.z };
	}

	Vector operator<<(int shift) const {
		return Vector{ x << shift, y << shift, z << shift };
	}

	Vector operator>>(int shift) const {
		return Vector{ x >> shift, y >> shift, z >> shift };
	}
};

int main() {
	Vector v0{ 0, 0, 0 };
	Vector v1;
	cout << v0 << endl;	// operator<<(cout, v) << endl;
	operator<<(cout, v0).operator<<(endl);
    // 위와 출력이 같은걸 볼 수 있다.
	cin >> v1;

	cout << v1 << endl;
	cout << ~v0 << endl;
	cout << (v0 & v1) << endl;
	cout << (v0 | v1) << endl;
	cout << (v1 << 1) << endl;
	cout << (v1 >> 1) << endl;
}
  • 실행 결과

    0 0 0
    0 0 0
    2 4 8
    2 4 8
    -1 -1 -1
    0 0 0
    2 4 8
    4 8 16
    1 2 4

profile
어중이떠중이

0개의 댓글