小甲鱼课程第25课,运算符重载
#include <iostream>class Complex
{
public:
Complex();
Complex(double r, double i);
Complex complex_add(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;
}
void Complex::print()
{
std::cout << "(" << real << ", " << imag << "i)\n";
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1.complex_add(c2);
std::cout << "c1 = ";
c1.print();
std::cout << "c2 = ";
c2.print();
std::cout << "c1 + c2 = ";
c3.print();
return 0;
}
question:
在执行加法操作的时候,
Complex Complex::complex_add(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
为什么在类内实例了一个c ?
因为重载的运算符 加 需要两个操作数,除了本身以外,还需要一个操作对象才行,而这里的对象就是本类的成员 Complex complex_add(Complex &d);
为什么 complex_add(Complex &d) 的前面要叫类名Complex? asking-2015 发表于 2019-5-2 21:46
Complex complex_add(Complex &d);
为什么 complex_add(Complex &d) 的前面要叫类名Complex?
我好像知道原因了,是不是因为Complex 是他的返回类型,即返回一个class Complex 类型的值。
页:
[1]