const引用和constexpr

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

猜你喜欢

转载自www.cnblogs.com/boost/p/10352539.html