有没有一种有效的方法来引用常量,实际上是const而不是只读? [英] Is there an efficient way to make reference to constants actually const instead of read only?

查看:119
本文介绍了有没有一种有效的方法来引用常量,实际上是const而不是只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看下面的C ++代码:

Let's look at the following C++ code:

#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类内部不能被修改,它只是意味着它是只读的,因为我可以从外部改变它的值。

It clearly shows that while inside class A x can't be modified, it merely means it's read only, because I can change it's value from outside.

当然,我可以让它存储在类A中的副本,但我想知道是否有(或者有提案?)一个方法来说,类A,成员x将是真正的恒定,而不是只是只读,意味着外部代码不会改变它的承诺?

Of course I can make it a copy stored inside class A, but I'm wondering if there is (or if there is a proposal?) of a way to say to class A that the member x will be truly constant instead of merely read only, with the meaning of a promise that the external code won't change it ?

对我来说,它看起来像是与C restrict 关键字,但我还没有听说过任何这样的C ++功能。你是吗?

To my eyes it looks like something related to the meaning of the C restrict keyword, but I've not heard of any such C++ feature yet. Do you ?

推荐答案

Constness是实际变量的属性。

Constness is an attribute of the actual variable.

const int& x 只是意味着x是对int的引用,它不会被修改,当然编译器强制这样做。

The term const int& x simply means "x is a reference to an int which it will not modify" and of course the compiler enforces this.

x指向的实际变量是const,简单地声明为:

If you want the actual variable to which x refers to be const, simply declare it so:

#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.

这篇关于有没有一种有效的方法来引用常量,实际上是const而不是只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆