常规: 通过调用方法实现,让 ‘+’实现两个对象(负数)相加
#include <iostream>
class Complex
{
public:
Complex();
Complex(double r,double i);
Complex Complex_add(Complex &d); //普通的函数调用
//Complex operator+(Complex &d); //运算符重载
void print();
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r,double i)
{
real = r;
imag = i;
}
Complex Complex::Complex_add(Complex &d)
{
Complex c;
c.real = real+d.real;
c.imag = imag + d.imag;
return c;
}
Complex Complex::operator+(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
void Complex::print()
{
std::cout << "(" <<real<<","<<imag<<")"<<std::endl;
}
int main()
{
Complex a(1,2),b(3,4),c;
a.print();
b.print();
c = a.Complex_add(b);
// c = a + b;
c.print();
return 0;
}
重载运算符 +,实现两个对象相加
```c
#include <iostream>
class Complex
{
public:
Complex();
Complex(double r,double i);
// Complex Complex_add(Complex &d); //普通的方法调用
Complex operator+(Complex &d); //运算符重载
void print();
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r,double i)
{
real = r;
imag = i;
}
Complex Complex::Complex_add(Complex &d)
{
Complex c;
c.real = real+d.real;
c.imag = imag + d.imag;
return c;
}
Complex Complex::operator+(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
void Complex::print()
{
std::cout << "(" <<real<<","<<imag<<")"<<std::endl;
}
int main()
{
Complex a(1,2),b(3,4),c;
a.print();
b.print();
//= a.Complex_add(b);
c = a + b;
c.print();
return 0;
}
使用友元函数实现运算符重载:
#include <iostream>
class Complex
{
public:
Complex();
Complex(double r,double i);
Complex Complex_add(Complex &d); //普通的函数调用
// Complex operator+(Complex &d); //运算符重载
friend Complex operator+(Complex &c,Complex &d); //运算符重载
void print();
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r,double i)
{
real = r;
imag = i;
}
Complex Complex::Complex_add(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
//这里是,友元函数的实现,不需要:域作用符,但友元函数会破坏类的封装性,所以一般不推荐
Complex operator+(Complex &a,Complex &b)
{
Complex c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return c;
}
void Complex::print()
{
std::cout << "(" <<real<<","<<imag<<")"<<std::endl;
}
int main()
{
Complex a(1,2),b(3,4),c;
a.print();
b.print();
c = a + b;
c.print();
return 0;
}
来源:CSDN
作者:qq_1316238389
链接:https://blog.csdn.net/qq_38173631/article/details/104178430