cpp学习笔记

侯捷学习笔记

  • 总结:
    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字节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值