建立一个test类:
class test
{
private:
int a;
double b;
double c;
public:
test(double);
friend test operator+(const test&,const test&);
test operator&(double);
void show(){cout<<c<<endl;}
enum{M=10};
};
转换函数:构造函数只接受一个参数:
test::test(double t)
{
a=(int)t%M;
b=int(t)%M;
c=t;
}
使用友元函数重载加法
test operator+(const test &t1,const test &t2) //友元函数
{
double x=t1.c+t2.c;
test sum(x); //新建sum对象,隐式调用构造函数
return sum;
}
将&重载为一个显式使用double类型的参数转换为test类型参数的函数
test test::operator&(double t)
{
double x=c+t;
test sum(x);
return sum;
}
我们来看调用这两个函数:(屏蔽当前的,取消一个屏蔽的,看会不会报错)
int main()
{
test dx(13.45);
double dob=2.3;
double dob1=2.5;
//测试friend test operator+(const test&,const test&);
test total=dob+dx; //正确
//test total=dx+dob; //正确
//test total=dob+dob1; //正确
//测试 test operator&(double)
//test total=dx&dob; //正确
//test total=dob&dx; //错误,实参类型与形参不匹配
total.show();
return 0;
}
友元函数的形参为
test operator+(const test &,const test &)
为什么test total=dob+dob1;
可以呢?
因为调用时dob/dob1为double类型的,因此将调用test(double)
构造函数将该参数转换为test
对象