侯捷学习笔记
- 总结:
1.头文件加上防卫式声明
2.二元运算符基本都用友元函数重载
3.一元运算符采用多种形式,要多考虑,需要在外部进行重载
4. .表示结构体(class)访问成员,—>表示结构体指针访问成员
5.尽可能使用引用传递,如果返回的是临时变量,不能使用引用传递
6.构造函数要使用高级一点的初始化列表
7.局部变量的构造法 typename(这里放要输出的结果);
1.头文件需要加上防卫式声明
#ifndef mycpp_complex_h
#define mycpp_complex_h
#endif
class complex{
public:
complex(int a=0;b=0): re(a),im(b){}//把a设给re,把b设给im
complex():re(a),im(b){}这个无参构造和前一个发生冲突
private:
int re;
int im;
{
complex c1(2,1);
cout<<c1.re;
cout<<c2.im;
}
//上述在数据式private时无法被调用
//要采用接口
不带指针的类多半不需要析构函数
- 参数传递:pass by value vs. pass by reference(to const)
pass by value 整包传递,不合理
c语言中用指针传递,传递value的地址
c++中传引用,相当于c中传指针,速度很快,尽可能传引用 - 返回值传递:return by value vs. return by reference (const)
尽可能传递引用,但如果返回的是一个局部变量,那就不能用引用
//return by reference
//语法分析
inline complex&
__doapl(complex*ths,const complex&r)
{
...
return *ths;
}
inline complex&
complex::operator +=(const complex &r)
{
return __doapl(this,r);
}
重载操作符
inline complex operator+(const complex &x,const compplex&y)
{
return complex(real(x) + real(y),imag(x)+image(y));
//加好之后一定是局部变量,所以不能返回reference
}
inline complex operator+(const complex &x,double y)
{
return complex(real(x) + y,imag(x));
//typename(临时对象)创建一个临时对象,虽然没有名字,但是可以返回value
}
inline complex operator+(double x,const complex &y)
{
return complex(real(y) + x,imag(y));
}
inline complex operator +(const complex &x)
{
return x;
}
inline complex operator -(const complex &x){
return complex(-real(x),-image(x));
}
inline bool operator ==(const complex &x,const complex &y){
return real(x)==real(y);
}
inline complex conj(const complex &x)
{
return complex(real(x),-image(y));
}
//重载<<操作符,只能选择全局函数
ostream& operator <<(ostream& os,const complex& x){
return os<<'('<<real(x)<<','<<image(x)<<')';
}
为什么+要设置为全局函数,如果放进class里面就无法解决常数+复数的情况
inline complex operator+(const complex& x, const complex& y){
return complex(real(x)+real(y),imag(x)+imag(y));
}
inline complex operator+(const complex& x,int y){
return complex(real(x)+y,imag(x));
}
重载输出
ostream& operator<<(ostream& os,const complex& x){
os<<"("<<x.real()<<","<<x.imag()<<")";
}
.用于结构体变量访问成员
→用于结构体指针变量访问成员
只要有一个虚函数就会多一个指针,4字节