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;
}