1.const 指针
- eg:
- (1) int const * p = nullptr;
- p = new int[10];
- p[3] = 4; //error
我们发现第三行没法编译, 这是因为第一行的 const 限制的时 int, 意思就是无法改变 p 所指的 int 类型的值.
- (2) int * const p = nullptr;
- p = new int [10]; //error
这是为什么呢? 原来时因为 const 限定的是 int*, 也就是限定的是指向 int * 的指针, 也就是 p 指针; 所以第二行是报错的. 因为 p 已经有了 nullptr,
(3) const int * p 和 int const * p 是一个道理;
2.const 引用
const 引用通常比 const 指针简单, 原因有两个:
第一: 引用默认为 const 无法改变引用所指的对象, 所以不需要显示的指出 const.
第二: 引用无法创建引用的引用, 只可能是有一层间接的取值, 获取多层间接的取值唯一方法就是创建指针的引用.
- eg:int a;
- const int & aRef = a;
- aRef = 2; //error
值得注意的是: const int & aRef = a; 与 int const & aRef = a; 是一样的;
因为 const 引用与 int 所以没办法改变 aRef 的值, 但是不会影响 a 的改变.
- int a = 3;
- int const & aRef = a;
- std::cout << aRef << std::endl; //aRef = 3;
- a = 5;
- std::cout << aRef << std::endl; //aRef = 5;
3.constexpr 关键字
C++ 一直存在常量表达式的概念,
有的时候不使用 constexpr 是不合适的,
- eg: int getValue(){
- return 10;
- }
- int arrayInt[getValue()]; //error
但是这样是可以的:
- constexpr int getValue()
- {
- return 10;
- }
- int arrayInt[getValue()]; //OK
需要注意的是 constexpr 是由一些限制的:
例如:
函数体是一个有 return 语句, 不包含 goto 语句和 try catch 块, 也不抛出异常, 但是可以调用其他的 constexpr 函数
constexpr 函数必须返回字面量类型. 返回值不能是 void
如果 constexpr 是一个类的成员函数, 则他不能是 virtual 函数
函数的所有参数都应该是字面量类型
不允许使用 dynamic_cast
不允许使用 new 和 delete.
- class Rect
- {
- public:
- constexpr Rect(int inWidth,int inHeight)
- :mWidth(inWidth)
- ,mHeight(inHeight)
- {
- }
- constexpr int getRect() const
- {
- return mWidth * mHeight;
- }
- private:
- int mWidth,mHeight;
- };
- int main(int argc, char** argv)
- {
- Rect rect(2,5);
- std::cout << "Rect's area : " << rect.getRect() <<
- std::endl;
- return 0;
- }
结果是: Rect's area : 10
来源: http://www.bubuko.com/infodetail-2945183.html