一道选择题:
计算机假定要对类AB定义加号操作符重载成员函数,实现两个AB类对象的加法,并返回相加结果,则该成员函数的声明语句为()
正确答案应为 AB operator+(AB&A) ,而我选择了 AB operator+(AB&A,AB&B)
这两者有什么区别呢
成员函数操作两个对象时,只需传递一个对象参数,另一个是调用成员的的this。
友员函数则需要两个对象参数,具体可以参考:
http://blog.csdn.net/wangkechuang/article/details/8002752
1. 成员函数重载运算符的例子:
#include<bits/stdc++.h>
using namespace std;
class Complex
{
public:
Complex(double real = 0, double imag = 0);
Complex operator+(Complex& com);
void output();
private:
double real;
double imag;
};
Complex::Complex(double newReal,double newImag)
{
this->real=newReal;
this->imag=newImag;
}
Complex Complex::operator+(Complex& com) //重载运算符 + 的形式
{
double treal = real + com.real;
double timag = imag + com.imag;
Complex a(treal,timag);
return a;
}
void Complex::output()
{
printf("real = %f , imag = %f \n",this->real,this->imag);
}
int main()
{
Complex a(1.2, 2.1);
Complex b(2.1, 1.1);
Complex c = a + b;
c.output();
}
正常工作
2. 友元函数的例子:
#include<bits/stdc++.h>
using namespace std;
class Complex
{
public:
Complex(double real = 0, double imag = 0);
void output();
friend Complex operator+(Complex& a,Complex& b);
//友元运算符形式
private:
double real;
double imag;
};
Complex::Complex(double newReal,double newImag)
{
this->real=newReal;
this->imag=newImag;
}
Complex operator+(Complex& a,Complex& b)
{
Complex c(a.real + b.real,a.imag + b.imag);
return c;
}
void Complex::output()
{
printf("real = %f , imag = %f \n",this->real,this->imag);
}
int main()
{
Complex a(1.2, 2.1);
Complex b(2.1, 1.1);
Complex c = a + b;
c.output();
}
这里可能不太熟悉的一点是,友元函数的实现中是没有Complex::的,因为是“友元”,不属于在类的内部。另外一点是,同一个运算符的重载,不能同时有成员函数和友元函数,不然容易引起歧义。