本文介绍了函数中的C ++ const关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  int getX()const {...} 

表示此函数不会修改任何在其正文中使用的变量。但是我didnt undertsnad在2个地方使用了const,如下所示:

  const int * getX()const {.. 。

const 关键字之前 int *

解决方案

您的第一个解释是错误的

  int getX()const {...} 

是一个成员函数,它不能修改任何数据成员,也不能为具有该函数的类的给定实例调用任何非const。

  const int * getX()const {...} 

返回一个 const int * ,所以它限制了你可以分配给它的东西。它是一个非const的指向const int的指针,所以你不能修改它指向的int,但你可以修改指针本身。例如:

  const int * i = someInstange.getX(); // getX()返回const int * 
i = someOtherFunction(); //另一个函数返回const int *。好,重新分配我。

因此 i 本身不是 const ,但它指向的是:

 (* i)++ ; //错误! 

如果您想要将 const指针返回给const int ,您需要像这样:

  const int * const getX(){} 

整个问题更加复杂,因为您可以在不改变含义的情况下将第一个 const 放在不同的位置。有关更多信息,请参阅。


I understand when using it as follows:

int getX() const {...}

means that this function will not modify any of the variables used in its body. But what I didnt undertsnad is using const in 2 places, like the following:

const int* getX () const {...}

what's the use of putting the const keyword before the int*?

解决方案

Your first interpretation is wrong.

int getX() const { ... }

is a member function, and it cannot modify any data members or call any non-const for a given instance of the class that has that function.

const int* getX() const { ... }

returns a const int*, so it limits what you can assign to using it. It is a non-const pointer to const int, so you cannot modify the int it points to, but you can modify the pointer itself. For example:

const int* i = someInstange.getX(); // getX() returns const int*
i = someOtherFunction(); // another function returning const int*. OK to reassign i.

So i itself isn't const, but what it points to is:

(*i)++; // ERROR!

if you wanted to return a const pointer to const int you would need something like this:

const int * const getX() {}

The whole issue is further complicated because you can put the first const in different places without changing the meaning. For more information on that, look at this SO question.

这篇关于函数中的C ++ const关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:36