Why is a non-static data member reference not a variable?

我的未来我决定 提交于 2019-12-04 00:49:56

问题


The definition of a variable in C++11 is as follows (§3/6):

A variable is introduced by the declaration of a reference other than a non-static data member or of an object. The variable’s name denotes the reference or object.

So a non-static data member reference is not a variable. Why is this distinction necessary? What's the rationale here?


回答1:


Here's one way I can declare a variable in C++:

int scientist = 7;

After this declaration (and definition, in this case), I can use scientist to read and set its value, take its address, etc. Here's another kind of declaration:-

class Cloud {
    public:
    static int cumulonimbus = -1;
};

This one is a bit more complicated, because I have to refer to the new variable as Cloud::cumulonimbus, but I can still read and set its value, so it's still obviously a variable. Here's a yet different kind of declaration:-

class Chamber {
    public:
    int pot;
};

But after this declaration, there isn't a variable called pot, or Chamber::pot. In fact there's no new variable at all. I've declared a new class, and when I later declare an instance of that class it will have a member called pot, but right now, nothing is called that.

A non-static data member of class doesn't create a new variable itself, it just helps you to define the properties of the class. If it did create a new variable, you'd be able to write code like this:

class Chamber {
    public:
    int pot;
};

void f(bool b) {
    if (b)
        Chamber::pot = 2;
}

What would that even mean? Would it find every instance of Chamber and set all their pots to 2? It's a nonsense.

A quick footnote: the language of the standard here is talking specifically about references, but to make the examples easier, I've been using non-references. I hope you can see this doesn't change the principle of it.



来源:https://stackoverflow.com/questions/12987259/why-is-a-non-static-data-member-reference-not-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!