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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.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有什么用途?_C++_Constants - Fatal编程技术网

C++ 当函数更改成员变量时,给定函数中的const有什么用途?

C++ 当函数更改成员变量时,给定函数中的const有什么用途?,c++,constants,C++,Constants,当函数更改成员变量时,const有什么用???不能在const对象(或指向const对象的ref或指针)上调用未标记const的方法 但是,这意味着从标记为const的方法中访问的所有数据成员也是const,因此您无法更改它们(不耍花招) 这就是为什么您的setx不会编译--x在这些方法中是常量 当成员变量被 功能 正如@songyuanyao正确提到的,导致编译错误 然而,这是一种惯例。您仍然可以通过上的const_cast或通过标记成员可变来修改成员 如前所述,逻辑常数和物理常数之间存在差异

当函数更改成员变量时,const有什么用???

不能在
const
对象(或指向
const
对象的ref或指针)上调用未标记
const
的方法

但是,这意味着从标记为
const
的方法中访问的所有数据成员也是
const
,因此您无法更改它们(不耍花招)

这就是为什么您的
setx
不会编译--
x
在这些方法中是常量

当成员变量被 功能

正如@songyuanyao正确提到的,导致编译错误

然而,这是一种惯例。您仍然可以通过
上的
const_cast
或通过标记成员
可变来修改成员

如前所述,逻辑常数和物理常数之间存在差异

为什么我们仍然可以修改
const
方法中的
非const
静态
成员

类的
非静态
方法将
this
作为参数<方法上的code>const
限定符使
保持不变(并在违反约定时触发编译错误)


静态
成员与
没有任何关系:它是类中每个对象的唯一成员。这就是为什么一个方法的常量(即
this
的常量)对类的
静态成员没有影响。

“const…”的用法是什么导致编译器错误?看起来您错误地将setters设置为常量,而getter设置为非常量。应该是相反的。这些东西都应该在类定义中,而不是在类定义之后。
x
是静态的,所以它不受
setx
@Caleth fixed上的
const
限定的影响,谢谢:)我没有发现它是静态的。
class StatDemo
{
   private: static int x;
   int y;
   public: void setx(int a) const { x = a; }
   void sety(int b) const { y = b; }
   int getx() {return x; }
   int gety() {return y; }
} ;
StatDemo sd;
StatDemo const & sdr = sd;
sdr.get(x); // error because getx isn't marked const