类的函数声明中“ const”最后的含义?

[亡魂溺海] 提交于 2019-12-24 17:38:03

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

像这样的声明中const的含义是什么? const使我感到困惑。

class foobar
{
  public:
     operator int () const;
     const char* foo() const;
};

#1楼

当您使用const方法签名(像你说: const char* foo() const; )你告诉编译器内存指向this不能用这种方法来改变(这是foo这里)。


#2楼

C ++常识中 Const成员函数的含义 :基本中级编程给出了明确的解释:

X类的非常量成员函数中的this指针的类型为X * const。 也就是说,它是指向非常量X的常量指针(请参见常量指针和指向常量的指针[7,21])。 因为此对象所指向的对象不是const,所以可以对其进行修改。 在类X的const成员函数中,此类型为const X * const。 也就是说,它是指向常量X的常量指针。由于此对象所指向的对象是const,因此无法对其进行修改。 这就是const和非const成员函数之间的区别。

因此,在您的代码中:

class foobar
{
  public:
     operator int () const;
     const char* foo() const;
};

您可以这样认为:

class foobar
{
  public:
     operator int (const foobar * const this) const;
     const char* foo(const foobar * const this) const;
};

#3楼

我想补充以下几点。

您也可以将 const &const &&

所以,

struct s{
    void val1() const {
     // *this is const here. Hence this function cannot modify any member of *this
    }
    void val2() const & {
    // *this is const& here
    }
    void val3() const && {
    // The object calling this function should be const rvalue only.
    }
    void val4() && {
    // The object calling this function should be rvalue reference only.
    }

};

int main(){
  s a;
  a.val1(); //okay
  a.val2(); //okay
  // a.val3() not okay, a is not rvalue will be okay if called like
  std::move(a).val3(); // okay, move makes it a rvalue
}

随时改善答案。 我不是专家


#4楼

与函数声明一起使用的const关键字指定它是const成员函数 ,它将无法更改对象的数据成员。


#5楼

const表示该方法保证不会更改该类的任何成员。 即使对象本身被标记为const ,您也可以执行标记为该对象的成员:

const foobar fb;
fb.foo();

是合法的。

请参见C ++中“ const”的用途是什么? 欲获得更多信息。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!