- C++编程介绍
- 头文件与类的声明
- 构造函数
- inline函数,如果函数在class内定义完成,则自动成为inline候选函数。
-
/*example 1*/
class complex
{
public:
complex (double r = 0, double i = 0)
:re(r), im(i)
{} /*自动inline候选*/
complex& operator += (const complex&);
double real() const { return re; }/*自动inline候选*/
double imag{} const { return im; }/*自动inline候选*/
private:
double re, im;
friend complex& __doapl(complex*, const complex&);
};
/*example 2*/
inline double
imag(const complex& x)
{
return x.imag();
}
- 构造函数可以有很多个-overloading(重载)
{
...
complex(double r = 0, double i = 0)
:re (r), im (i)
{}
complex() : re(0), im(0){} /*有默认参数构造函数,不能同时存在该构造函数*/
double real() const { return re; } /*?real@Complex@@QBENXZ*/
void read(double r) { re = r; } /*?real@Complex@@QAENABN@Z*
...
}
{
complex c1;
complex c2();
...
}
- 操作符重载
-
操作符是如何被编译器看待的??
{
complex c1(2, 1);
complex c2(5);
c2 += c1; /*当编译器检测到+= 操作符的时候,会把这个操作符作用在前面的c2对象上*/
/*
inline complex&
complex::operator += (this, const complex& r)
{
return __doapl(this, r);
*/
}
so, 如何实现操作符的重载?
inline complex&
__doapl(complex& ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
/*为何返回的是complex&,而不是complex??->这样可以连续的使用操作符*/
inline complex&
complex::operator += (const complex& r)
{
return __doapl(this, r);
}
/*此处绝对不能用引用,因为+后的是一个临时对象,返回后就释放了,返回的引用就无效了*/
inline complex
operator + (const complex& x, const complex& y)
{
return complex(real(x) + real(y),
imag(x) + imag(y));
}