我们来看下面的 C++ 代码:
#include <iostream>
int main()
{
int z = 2;
class A {
public:
const int & x;
A(const int & x) : x(x) {}
void show(){
std::cout << "x=" << this->x << std::endl ;
}
} a(z);
a.show();
z = 3;
a.show();
}
程序打印:2 和 3
它清楚地表明,虽然 A x 类内部无法修改,但这仅仅意味着它是只读的,因为我可以从外部更改它的值。
当然,我可以将其作为存储在 A 类中的副本,但我想知道是否有(或者是否有建议?)有一种方法可以对 A 类说成员 x 将是真正的常量,而不仅仅是读取只是,其含义是外部代码不会改变它?
在我看来,它看起来像是与 C 的含义相关的东西restrict https://en.wikipedia.org/wiki/Restrict关键字,但我还没有听说过任何这样的 C++ 功能。你 ?
常量是实际变量的一个属性。
期限const int& x
只是意味着“x 是对 int 的引用,它不会修改它”,当然编译器会强制执行此操作。
如果您希望 x 引用的实际变量是 const,只需这样声明即可:
#include <iostream>
int main()
{
const int z = 2; // declared const. Nothing may ever modify it
class A {
public:
const int & x;
A(const int & x) : x(x) {}
void show(){
std::cout << "x=" << this->x << std::endl ;
}
} a(z);
a.show();
z = 3; // this is a logic error, caught by the compiler.
a.show();
}
正确编译会产生错误:
./const.cpp:41:7: error: read-only variable is not assignable
z = 3;
~ ^
1 error generated.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)