○演算子の宣言

■演算子 ( = + - * / など) の役割を宣言します

#include <stdio.h>

class test{
public :
	unsigned char a;
	void operator=(test obj){
		a=obj.a;
	}
	test operator+(test obj){
		test pos;
		pos.a=a+obj.a;
		return pos;
	}
	test operator-(test obj){
		test pos;
		pos.a=a-obj.a;
		return pos;
	}
	test operator*(test obj){
		test pos;
		pos.a=a*obj.a;
		return pos;
	}
	test operator/(test obj){
		test pos;
		pos.a=a/obj.a;
		return pos;
	}
	bool operator==(test obj){
		return a==obj.a;
	}
};



int main(){
	test a,b,c;

	a.a = 8;
	b.a = 2;

	c = a + b;
	printf("%d = a + b\n",c.a );

	c = a - b;
	printf("%d = a - b\n",c.a );

	c = a * b;
	printf("%d = a * b\n",c.a );	

	c = a / b;
	printf("%d = a / b\n",c.a );
	
	bool f = a == b;
	printf("%s = a == b\n",(f ? "true":"false"));	

	return 0;
}

処理結果
10 = a + b
6 = a - b
16 = a * b
4 = a / b
false = a == b




▲トップページ > Windows と C++