运算符重载

// zwdzjs.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <stdio.h>
#include "windows.h"


class MyClass
{
public:

	MyClass(int a,int b);

private:
	friend class Number;
	int a;
	int b;
};

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



class Number {
private:
	int lowValue;
	int highValue;
	friend class MyClass;  //声明 CDriver 为友元类
public:
	Number(int lowValue, int highValue);
	void Print();
	Number operator++(int);
	Number operator--(int);
	Number operator+(const MyClass& p);
	Number operator-(const Number& p);
	Number operator*(const Number& p);
	Number operator/(const Number& p);
	bool  operator<(const Number& p);
	bool  operator>(const Number& p);
	bool  operator==(const Number& p);
};

Number::Number(int lowValue, int highValue) {
	this->lowValue = lowValue;
	this->highValue = highValue;
	
}

void Number::Print() {
	printf("%d,%d\n", lowValue,highValue);
}

Number Number::operator++(int)
{
	lowValue++;
	highValue++;
	return *this;
}

Number Number::operator--(int)
{
	lowValue--;
	highValue--;
	return *this;
}


Number Number::operator+(const MyClass& p)
{
	this->lowValue =this->lowValue + p.a;
	this->highValue = this->highValue + p.b;
	return *this;
}

Number Number::operator-(const Number& p)
{
	this->lowValue = this->lowValue - p.lowValue;
	this->highValue = this->highValue - p.highValue;
	return *this;
}


Number Number::operator*(const Number& p)
{
	this->lowValue = this->lowValue * p.lowValue;
	this->highValue = this->highValue * p.highValue;
	return *this;
}

Number Number::operator/(const Number& p)
{
	this->lowValue = this->lowValue / p.lowValue;
	this->highValue = this->highValue / p.highValue;
	return *this;
}


bool Number::operator<(const Number& p)
{
	if (this->highValue > p.highValue)
	{
		return true;
	}
	return false;
}


bool Number::operator==(const Number& p)
{
	if (this->highValue == p.highValue)
	{
		return true;
	}
	return false;
}




bool Number::operator>(const Number& p)
{
	if (this->highValue > p.highValue)
	{
		return true;
	}
	return false;
}




int main(int argc, char* argv[])
{

	MyClass m(2, 5);
	Number n(1, 5);
	n.Print();
	//n--;
	//n.Print();
	//bool ns = n<m;

	n.Print();


	getchar();

	return 0;
}

发表评论 / Comment

用心评论~