这是《C++入门到实践》上的两个关于重载操作符再输出的两个源代码:(关于里面mian函数中将类对象输出的问题,为什么上面这个源代码可以直接用"cout<<"将类对象输出,而下面这个却不可以?)#include "stdafx.h"
#include <iostream>
#include <assert.h>
using namespace std;
class real
{
public:
real(double value=0);
real operator +(const real &real1); //加法运算
friend real operator *(const real &real1,const real &real2); //乘运算
friend real operator /(const real &real1,const real &real2); //除法运算
real operator -(const real &real1); //减法运算
double operator +(const double &d); //加法运算
real operator +(const int &i); //加法运算
int operator !()const; //非运算
real operator -()const; //求负
real operator +()const; //求正
real operator ++(); //右自增
real operator --(); //右自减
operator double()const; //类型转换
private:
double value;
};
//加法运算
real real::operator +(const int &i)
{
real temp;
temp.value=value+i;
return temp;
}
//加法运算
double real::operator +(const double &d)
{
return value+d;
}
//非运算
int real::operator !()const
{
return !value;
}
//减法运算
real real::operator -(const real &real1)
{
return real(this->value-real1.value);
}
//除法运算
real operator /(const real &real1,const real &real2)
{
real temp;
assert(real2.value);
temp.value=real1.value/real2.value;
return temp;
}
//构造函数
real::real(double value)
{
this->value=value;
}
//加法运算
real real::operator +(const real &real1)
{
return real(this->value+real1.value);
}
//求负
real real::operator -()const
{
return real(-value);
}
//求正
real real::operator +()const
{
return real(+value);
}
//右自增
real real::operator ++()
{
value++;
return real(value);
}
//右自减
real real::operator --()
{
value--;
return real(value);
}
//类型转换
real::operator double()const
{
return value;
}
//乘法运算
real operator *(const real &real1,const real &real2)
{
real temp;
temp.value=real1.value*real2.value;
return temp;
}
int main(int argc, char* argv[])
{
real r1(12.3);
real r2(20.8);
cout<<r1+r2<<endl;
cout<<-r1<<endl;
cout<<r1*r2<<endl;
cout<<++r1<<endl;
cout<<r1<<endl;
cout<<--r1<<endl;
cout<<r1<<endl;
return 0;
}
下面的:
#include "stdafx.h"
#include <iostream>
using namespace std;
class real //实数类
{
public:
real(double value=0);
real operator -()const; //重载"-"负运算
real operator ++(); //重载"++"自增运算
private:
double value;
};
real::real(double value)
{
this->value=value;
}
real real::operator -()const
{
return real(-value);
}
real real::operator ++()
{
value++;
return real(value);
}
int main(int argc, char* argv[])
{
real r1(12.3);
cout<<r1<<endl;
cout<<++r1<<endl;
cout<<r1<<endl;
cout<<-r1<<endl;
return 0;
} |