为什么非静态数据成员引用不是变量? [英] Why is a non-static data member reference not a variable?

查看:225
本文介绍了为什么非静态数据成员引用不是变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11中变量的定义如下(第3/6节):

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?

推荐答案

这是我可以在C ++中声明变量的一种方法:

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

int scientist = 7;

此声明(在本例中为定义)之后,我可以使用scientist读取并设置其值,获取其地址等.这是另一种声明:-

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;
};

这有点复杂,因为我必须将新变量称为Cloud::cumulonimbus,但是我仍然可以读取和设置其值,因此显然它仍然是变量.这是另一种声明:-

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;
};

但是在此声明之后,没有一个名为potChamber::pot的变量.实际上,根本没有新的变量.我已经声明了一个新类,并且稍后再声明该类的实例时,它将有一个名为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;
}

那甚至意味着什么?它会找到每个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.

这篇关于为什么非静态数据成员引用不是变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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