如果需要声明具有所有属性的类的const实例
It there a need to declare const instance of a class with all attributes const?
这是对具有所有属性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
。
相关文章:
- muQueue.front() 给出了 const 实例,即使我没有将其标记为 const
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在字符串函数中抛出'char const*'实例后调用的终止
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 自定义链表const_iterator无法遍历列表的非const实例
- 引发"char const*"错误的实例后调用的终止
- 无法用const char *数组实例化模板
- C++:具有 const int 的类的 vector.erase 实例给出"attempting to reference a deleted function"错误 C2280
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 如何处理 const T& 和 T&& 实例化到同一个签名?
- 我可以在类头文件中定义一个类的const静态实例吗
- 当丢失非const虚拟方法时,为什么我不能实例化类的const实例
- 当此实例为const时,请引发异常
- 复制MyGreatClass的const*实例的正确方法
- 自定义类的const实例化是否也会使类中的*everything*变为常量
- 为什么无法使用复制构造函数实例化"non const"而可以在没有复制构造函数的情况下实例化配对?
- 为什么我不能在复制构造函数中更改实例的私有数据,如果它是 const 的?
- 在抛出"char const*"实例后终止调用
- 如果需要声明具有所有属性的类的const实例