运算符重载:友元(friend)函数问题
来源:互联网 发布:ngxopenresty 解析php 编辑:程序博客网 时间:2024/06/05 17:05
运算符在重载的时候有两种方式,一是成员函数方式,二是成友元(friend)函数方式。
成员函数比较简单。下面是一个示例代码:
class Complex
{
private:
double real;
double img;
public:
Complex(){}
Complex(double i,double j):real(i),img(j)
{
}
Complex operator+(const Complex &cx)
{
return Complex(real+cx.real,img+cx.img);
}
};
如果是设置成友元函数,一定要注意:
(1)当重载友元函数时,将没有隐含的参数this指针。这样,对双目运算符,友元函数有2个参数,对单目运算符,友元函数有一个参数。
(2)有些运行符不能重载为友元函数,它们是:=,(),[]和->。
因此,上面那个+运算符如果是重载为友元函数的话,应该写成:
class Complex
{
private:
double real;
double img;
public:
Complex(){}
Complex(double i,double j):real(i),img(j)
{
}
// 注意: 有两个参数
friend Complex operator+(const Complex &cx1,const Complex &cx2)
{
return Complex(cx1.real+cx2.real,cx1.img+cx2.img);
}
void Out()
{
cout << real << "+" << img << "i" << endl;
}
};
还需要注意一点,有的VC 6.0编译器在编译上面代码的时候会报错,错误为:
fatal error C1001: INTERNAL COMPILER ERROR
原因是VC编译器本身的问题。
解决办法: 在类的声明之前再加上一个声明。具体代码如下:
class Complex;
Complex operator+(const Complex &cx1,const Complex &cx2);
class Complex
{
private:
double real;
double img;
public:
Complex(){}
Complex(double i,double j):real(i),img(j)
{
}
// 注意:有两个参数
friend Complex operator+(const Complex &cx1,const Complex &cx2)
{
return Complex(cx1.real+cx2.real,cx1.img+cx2.img);
}
void Out()
{
cout << real << "+" << img << "i" << endl;
}
};
这样就没有问题了。
以下 是简单的 运算符重载代码:
#include<iostream>#include<string>using namespace std;class LCF2{private:int c;public: LCF2(int c1):c(c1){}~LCF2(){}LCF2(LCF2 & other){c=other.c; }friend ostream& operator<<(ostream& os,LCF2 & lcf2){os<<lcf2.c<<endl;return os;} LCF2& operator = (LCF2 & lcf2){ this->c=lcf2.c;return *this;}friend LCF2 & operator +=(LCF2& lcf1,LCF2& lcf2){lcf1.c = lcf1.c+lcf2.c;return lcf1;}friend LCF2 & operator -=(LCF2& lcf1,LCF2& lcf2){lcf1.c=lcf1.c-lcf2.c;return lcf1;}};int main() { LCF2 lcf2(1); LCF2 lcf3(2); LCF2 lcf4(3); LCF2 lcf5(lcf4);//初始化 进入拷贝构造函数 cout<<lcf5; cout<<lcf2<<endl; lcf2=lcf3; cout<<lcf2; lcf2+=lcf3; cout<<lcf3; cout<<lcf2; cout<<lcf4; lcf4-=lcf3; cout<<lcf4; system("pause"); return 0; }