对象的常量函数
class complex
{
public:
complex(double r, double i = 0):re(r), im(i)
{}
complex() :re(1), im(0)
{}
complex& operator += (const complex&); //返回一个引用型 //引用传值类似指针,比值传递快
double real() const { return re; } //返回一个double型
double imag() const { return im; }
private:
double re, im;
friend complex& _doapl(complex*, const complex);
};
int main()
{
/*complex c1(2, 1);
cout << c1.real() << "+i";
cout << c1.imag();*/
const complex c2(2, 5);
cout << c2.real() << "+i"; //double real() { return re; },不能将“this”指针从“const complex”转换为“complex &”
cout << c2.imag();
cout << endl;
return 0;
}
运算符重载 - 复数
class complex
{
public:
complex(double r, double i = 0):re(r), im(i)
{}
complex() :re(1), im(0)
{}
double real() const { return re; }
double imag() const { return im; }
int func(const complex& param)
{
return param.im + param.re;
}
complex& operator += (const complex& r)
{
return _doapl(this, r);
}
private:
double re, im;
friend complex& _doapl(complex* ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
};
int main()
{
complex c1(2, 5);
complex c2(6);
c2 += c1;
cout << c2.real() << " +i" << c2.imag() << endl;
cout << endl;
return 0;
}
相同class的各个objects互为友元
class complex
{
public:
complex(double r, double i = 0):re(r), im(i)
{}
complex() :re(1), im(0)
{}
int func(const complex& param) //不会报错
{
return param.im + param.re;
}
private:
double re, im;
};
int main()
{
complex c1(2, 5);
complex c2;
cout << c2.func(c1) << endl;
cout << endl;
return 0;
}
+=符号重载
class complex
{
public:
complex(double r, double i = 0):re(r), im(i)
{}
complex() :re(1), im(0)
{}
double real() const { return re; }
double imag() const { return im; }
int func(const complex& param)
{
return param.im + param.re;
}
complex& operator += (const complex& r)
{
return _doapl(this, r);
}
private:
double re, im;
//返回值为complex不是void,为了防止c3 += c2 += c1不能执行
friend complex& _doapl(complex* ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
};
int main()
{
complex c1(2, 5);
complex c2(6);
c2 += c1;
cout << c2.real() << " +i" << c2.imag() << endl;
cout << endl;
return 0;
}