effective C++ 读书笔记(3)

本文深入探讨了C++中const成员函数的使用原则与常见误解,包括const成员函数之间的调用关系、const成员函数与非const成员函数的相互作用,以及如何正确理解和应用const成员函数以避免潜在的编程错误。

1:P18 页 

  经过我的实验

  void f1(const A * a);

 和void f2(A const *a);

是不同的!  莫非书上有错?

2: STL迭代器 天生就是 T *const ptr

       如果需要一个 const T* ptr 则需要的是 const_iterator

3: 

  这个表要记一下子

      对象          成员函数       对/错

1、  const         const           对
2、  const         non-const       错
3、  non-const     const           对
4、  not-const     non-const       对



          成员函数调用成员函数

     成员函数      成员函数       对/错
5、  const         const           对
6、  const         non-const       错
7、  non-const     const           对
8、  non-const     non-const       对

class A

{

public:

int style;

static const int num = 5;

enum {numEnum = 5};

int scores[num];

int shit[numEnum];

template <class T>

inline const T& callWithMax(const T& a,const T& b)

{

return (a>b?a:b);

}

int getNum()

{

cout<<"normal"<<endl;

return style;

}

const int getNum() const

{

cout<<"const"<<endl;

return style;

}

A(int temp):style(temp){};

};

int main()

{

A normalA(10);

cout<<normalA.getNum()<<endl;  // cout normal

const A constA(20);

cout<<constA.getNum()<<endl;  // cout const

return 0;

}

3: const 成员函数 可以调用 非cosnt 的相同版本 从而起到 节省代码量的作用

class A

 

{

public:

int style;

static const int num = 5;

enum {numEnum = 5};

int scores[num];

int shit[numEnum];

template <class T>

inline const T& callWithMax(const T& a,const T& b)

{

return (a>b?a:b);

}

int& getNum()

{

cout<<"normal"<<endl;

return const_cast<int&>((static_cast<const A*>(this))->getNum());

}

const int& getNum() const

{

cout<<"const"<<endl;

return style;

}

A(int temp):style(temp){};

};

int main()

{

A normalA(10);

cout<<normalA.getNum()<<endl;  // cout normal const

const A constA(20);

cout<<constA.getNum()<<endl;  // cout const

return 0;

}

 注意! 反向的做法是一个很冒险的行为!

class A

    

{

public:

int style;

static const int num = 5;

enum {numEnum = 5};

int scores[num];

int shit[numEnum];

template <class T>

inline const T& callWithMax(const T& a,const T& b)

{

return (a>b?a:b);

}

int& getNum()

{

cout<<"normal"<<endl;

return style;

}

const int& getNum() const

{

cout<<"const"<<endl;

return static_cast<int&>((const_cast<A *>(this))->getNum());

}

A(int temp):style(temp){};

};

int main()

{

A normalA(10);

cout<<normalA.getNum()<<endl;  // cout normal

const A constA(20);

cout<<constA.getNum()<<endl;  // cout const normal

return 0;

}

转载于:https://www.cnblogs.com/wangshuai901/archive/2011/09/07/2169670.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值