Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否需要声明具有所有属性const的类的const实例?_C++_C++11_Attributes_Constants_Member Functions - Fatal编程技术网

C++ 是否需要声明具有所有属性const的类的const实例?

C++ 是否需要声明具有所有属性const的类的const实例?,c++,c++11,attributes,constants,member-functions,C++,C++11,Attributes,Constants,Member Functions,这是一个后续行动 所以我有一个类置换组,它的所有属性都是常量。编译器仍然区分常量和非常量实例: struct Foo { const int bar; void meth(); }; int main() { Foo foo {2}; foo.meth(); // correct const Foo cfoo {1}; cfoo.meth(); // wrong }; bla.cpp: In function ‘int mai

这是一个后续行动

所以我有一个类
置换组
,它的所有属性都是常量。编译器仍然区分常量和非常量实例:

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

   const Foo cfoo {1};
   cfoo.meth();         // wrong
};
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();
正如@nosid在提到的问题中所注意到的,不能将非
const
成员函数调用为const实例:

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

   const Foo cfoo {1};
   cfoo.meth();         // wrong
};
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
实例,一个可能的原因就是您不能编写以下代码:

class Foo { Foo(void) const; };
其中提出:

error: constructors may not be cv-qualified

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

的可能副本。请尝试解决您原来的问题@πάντα ῥεῖ: 我不想改变我原来帖子上的问题。而且我也没什么问题。我更想知道好的做法。了解一下,为什么这对你很重要,这会很有帮助。为什么不将成员函数声明为const呢?为什么要将成员变量声明为常量?这并不常见。@nosid:我在为数学对象建模。它们不会随着时间而改变。例如,整数1永远不会变为2。另一个更有意义的例子:修改所有整数的集合没有任何意义。@hivert:
int
也是数学对象,但它们是可变的。在我看来,这是关于对象标识,而不是关于易变性。