重载操作符简例
#include <stdio.h>
class Fraction
{
public:
Fraction()
{
numerator = 0;
denominator = 1;
}
Fraction(int a, int b)
{
numerator = a;
denominator = b;
}
Fraction operator + (const Fraction &other)//使分数类支持加法
{
Fraction result;
result.denominator = this->denominator * other.denominator;
result.numerator = this->numerator*other.denominator + other.numerator*this->denominator;
return result;
}
operator double()//使分数类支持向double的强制转换
{
return (double)numerator/denominator;
}
bool operator == (const Fraction &other)//如果两个分数相等则返回true,否则返回false
{
if (this->numerator*other.denominator == this->denominator * other.numerator)
{
return true;
}
return false;
}
protected:
private:
int numerator;
int denominator;
};
int main()
{
Fraction a(2,3);
Fraction b(4,6);
double value = (double)a;
if (a == b)
{
printf("haha! %f\n", value);
}
return 0;
}