它有没有需要声明一个类常量实例的所有属性常量? [英] It there a need to declare const instance of a class with all attributes const?
问题描述
这是一个后续到<一个href=\"http://stackoverflow.com/questions/23449597/does-a-class-with-all-attributes-const-need-to-have-member-function-declared-con/23449626?noredirect=1#23449626\">Does所有的一类属性常量需要有成员函数声明为const呢?。
所以我一类 PermutationGroup
,其所有属性都是常量。编译器仍然让const和非const实例之间的区别:
So I've a class PermutationGroup
whose all attribute are const. The compiler still make the distinction between const and non-const instance:
struct Foo {
const int bar;
void meth();
};
int main() {
Foo foo {2};
foo.meth(); // correct
const Foo cfoo {1};
cfoo.meth(); // wrong
};
正如提到的问题注意到了@nosid一个不能调用非常量
成员函数一个const实例:
As noticed by @nosid in the referred question One cannot call a non const
member function a const instance:
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的实例。有没有合理的利用呢?
So the question is: why is it possible to declare non const instance of a class whose attribute are all const. Is there any reasonable use of that ?
推荐答案
好了,的可能的,为什么它应该被允许申报一个非推理 - 常量
例如在一个类,其成员都是常量
很简单,就是你不能写以下code的事实:
Well, a possible reasoning on why it should be allowed to declare a non-const
instance in a class whose members are all const
is simply the fact that you can't write the following code:
class Foo { Foo(void) const; };
这引发了:
error: constructors may not be cv-qualified
这意味着,至少有一个成员 - 构造函数,当然析构函数 - 始终是非 - 常量
这篇关于它有没有需要声明一个类常量实例的所有属性常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!