1.首先给两种运算符重载的方式:
1.1一种为:友元函数
1.2另一种为:成员函数
代码如下:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Complex{
friend Complex operator +(const Complex &c1, const Complex &c2);
double real;
double imag;
public:
Complex(){}
Complex(double r, double i) :real(r), imag(i){}
Complex operator +(const Complex &c1)
{
cout << "running......"<<endl;
double r = c1.real + this->real;
double i = c1.imag + this->imag;
return Complex(r, i);
}
void print() const;
};
Complex operator +(const Complex &c1, const Complex &c2){
double r = c1.real + c2.real;
double i = c1.imag + c2.imag;
return Complex(r, i);
}
void Complex::print() const{
cout << real << "," << imag << endl;
}
int main()
{
Complex a(2.0, 2.0), b(3.0, 3.0), c;
c = a + b;
cout << "c=";
c.print();
system("pause");
}
2.
3.const 是常量 也是速度最快的编译者
4.所有情况下 都会优先调用成员函数
5. 重载就是重载 需要思考的时候隔离思考类
一定要对这句话有所想法,重载既然就是重载 ,我为什么要做友元函数呢,不做可不可以(PS:当然 主要为了深究这样写的原因,看完之后的,对这个可是相当打脸,毕竟不这么做的都是小孩子 ,哈哈^_^)
犯错的流程
背景为首先开始写的是友元函数的实现方式,我要改成员函数的实现方式
1.我去掉了在类里面写的代码
friend Complex operator +(const Complex &c1, const Complex &c2);
2.然后在类里面书写重载的成员函数
Complex operator +(const Complex &c1)
{
cout << "running......"<<endl;
double r = c1.real + this->real;
double i = c1.imag + this->imag;
return Complex(r, i);
}
3.然后报错了,原因在于我没有删除原本的友元函数
造成了访问方式的出错,由于默认函数里面的成员访问为private,下面的重载函数又不能作为友元函数,不能对private进行访问,因此出错了。代码如下:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Complex{
double real;
double imag;
public:
Complex(){}
Complex(double r, double i) :real(r), imag(i){}
Complex operator +(const Complex &c1)
{
cout << "running......"<<endl;
double r = c1.real + this->real;
double i = c1.imag + this->imag;
return Complex(r, i);
}
void print() const;
};
Complex operator +(const Complex &c1, const Complex &c2){
double r = c1.real + c2.real;
double i = c1.imag + c2.imag;
return Complex(r, i);
}
void Complex::print() const{
cout << real << "," << imag << endl;
}
int main()
{
Complex a(2.0, 2.0), b(3.0, 3.0), c;
c = a + b;
cout << "c=";
c.print();
system("pause");
}
最后我认为,重载归重载,类是类,不能混着想,写的时候一定要有清晰的区分,不然最后犯很多低级错误,就很难受。