计算裴波那切数列相邻项之比
这是我的代码
这是答案代码
这是我的输出
你的函数实现在哪呢?
class Complex{
public:
Complex(int r = 1,int i = 1):real_(r),image_(i){}
~Complex(){}
void print(){
std::cout<<"real_= "<<real_<<std::endl;
std::cout<<"image_= "<<image_<<std::endl;
}
Complex operator+(const Complex&right){
return Complex(this->real_+right.real_,this->image_+right.image_);
}
private:
double real_;
double image_;
};
我们这里,为了满足Complex对象之间进行加法运算的需求,实现了Complex的加法运算符重载函数,看上去好像没有什么问题,我们使用一下该接口,挨个分析下面每个加法case:
int main(){
Complex com1(100,1000);
Complex com2(99,999);
Complex com3 = com1 + com2;
com3.print();
Complex com4 = com1 + 5;
com4.print();
//Complex com5 = 6 + com1;
//com5.print();
return 0;
}
我们知道,运算符重载就相当于左边的对象调用自己的某个重载方法,将右边的值作为参数传递进去,这里也是一样的,相当于com1.operator+(com2)
,这个样子,这样自然没有什么问题,比较经典的对象加法运算;
同样的,这里相当于com1.operator+(5)
,这里实际上发生了一个类型的强转,将int类型强转成了Complex类型,生成了一个临时的Complex对象初始化了形参,这个临时对象实际是Complex(5,1),因为该类的构造函数有默认值,所以可以只给一个参数生成临时对象,
最终,即com1.operator+(Complex(5,1))
,也没什么问题的,目前该运算符重载函数依然可以满足要求。
此时6在左边,编译器没有理由将6强转成Complex对象,因为此时不像上面第二个例子中的5一样,5作为实参传递给了Complex类型的形参,编译器找到了合适的构造函数才将5进行强转,然后初始化形参的。
此时,编译器发现没有能够满足该类加法的类内的运算符重载,所以就会在全局作用域内寻找:
Complex operator+(const Complex&left,const Complex&right){
return Complex(left.real_+right.real_,left.image_+left.image_);
}
此时, Complex com5 = 6 + com1;相当于left 为Complex(6,1)这样的临时对象,right为com1,由于全局作用域无法访问类内的私有变量,所以需要将此方法在类内生命为firend.
class Complex{
public:
Complex(int r = 1,int i = 1):real_(r),image_(i){}
~Complex(){}
void print(){
std::cout<<"real_= "<<real_<<std::endl;
std::cout<<"image_= "<<image_<<std::endl;
}
Complex operator+(const Complex&right){
return Complex(this->real_+right.real_,this->image_+right.image_);
}
friend Complex operator+(const Complex&left,const Complex&right);
//不想用friend 也可以提供get real 和 get image方法,firend方便一点
private:
double real_;
double image_;
};
Complex operator+(const Complex&left,const Complex&right){
return Complex(left.real_+right.real_,left.image_+left.image_);
}
int main(){
Complex com1(100,1000);
Complex com2(99,999);
Complex com3 = com1 + com2;
com3.print();
Complex com4 = com1 + 5;
com4.print();
Complex com5 = 6 + com1;
com5.print();
return 0;
}
这里既提供了类内的运算符重载,也提供了全局的运算重载,编译器编译时,优先选择类内的,类内如果无法满足,就去全局找,如果全局都没法找到,那么就要编译报错了。