如果需要声明具有所有属性的类的const实例

It there a need to declare const instance of a class with all attributes const?

本文关键字:const 实例 属性 声明 如果      更新时间:2023-10-16

这是对具有所有属性const的类是否也需要将成员函数声明为const的后续问题。

我有一个类PermutationGroup,它的所有属性都是const。编译器仍然会区分const和非const实例:

struct Foo {
  const int bar;
  void meth();
};
int main() {
   Foo foo {2};
   foo.meth();          // correct
   const Foo cfoo {1};
   cfoo.meth();         // wrong
};

正如@nosid在提到的问题中注意到的那样,不能将非const成员函数调用为const实例:

bla.cpp: In function ‘int main()’:
bla.cpp:10:14: error: passing ‘const Foo’ as ‘this’ argument of ‘void Foo::meth()’ discards qualifiers [-fpermissive]
    cfoo.meth();

那么问题是:为什么可以声明一个属性都是const的类的非const实例?有什么合理的使用吗?

好吧,一个可能的原因是为什么应该允许在一个成员都是const的类中声明一个非const实例,原因很简单,你不能写下面的代码:

class Foo { Foo(void) const; };
提出了

:

error: constructors may not be cv-qualified

这意味着,至少有一个成员——构造函数,当然还有析构函数——将总是非const

相关文章: