简体   繁体   English

常量类成员不是常量-C ++

[英]constant class member not constant - C++

I wonder when I pass a value to a constant variable, why this variable can change. 我想知道何时将值传递给常量变量,为什么这个变量可以更改。

#include <cstdio>

struct point
{
    int x, y, z;
};

class A
{
    public:
        A(const point &p) :
           p(p)
        {
             printf("(%d,%d,%d)\n", p.x, p.y, p.z);
        }

        void do_smth()
        {
            printf("(%d,%d,%d)\n", p.x, p.y, p.z);
        }

        const point &p;
};

int main(int argc, const char *argv[])
{
    point p = {1, 1, 1};
    A a(p);
    p.y = 4;
    a.do_smth();
    return 0;
}

stdout: 标准输出:

(1, 1, 1)
(1, 4, 1)

I use g++ v4.7 with no extra arguments to compile this code. 我使用没有额外参数的g ++ v4.7来编译此代码。

Well, the Point inside the A class is constant, but as it's a reference to p which it not constant, you can change p as much as you like and the all references to p will change as well. 好吧, A类中的Point是恒定的,但是由于它是对p引用不是恒定的,因此您可以随意更改p ,并且对p的所有引用也会更改。 To simplify, references are just a kind of fancy pointer. 为简化起见,引用只是一种奇特的指针。

p itself is not const. p本身不是const。 Ap is... Referencing a non- const variable with a const reference doesn't magically make it const . Ap是...用const引用引用非const变量并不能使其神奇地成为const

const表示该值不能通过此引用更改,而不是根本不会更改。

You change the variable in place, where it is not constant. 您可以在不恒定的位置更改变量。 You cannot change it in do_smth() method, try it. 您无法在do_smth()方法中do_smth()更改,请尝试一下。

Passing to some class as constant doesn't change the object at all. 传递给某个类作为常量不会改变对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM