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

前端 未结 1 819
花落未央
花落未央 2021-01-02 04:25

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

相关标签:
1条回答
  • 2021-01-02 04:52

    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.

    0 讨论(0)
提交回复
热议问题