gpt4 book ai didi

c++ - 非静态非引用数据成员声明变量吗?

转载 作者:太空狗 更新时间:2023-10-29 20:10:06 24 4
gpt4 key购买 nike

我想根据以下答案和附加讨论重新提出一个问题:
Why is a non static data member reference not a variable? :

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.


但是,在当前n4296 c++17 draft变量仍然定义为 (§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, if any, denotes the reference or object.

已接受 答案中的论点对我来说似乎合乎逻辑,但根据我对上述变量定义的理解,它与标准相冲突。

问题 是非静态非引用数据成员声明变量,如果是,为什么它们被认为是这样,因为我不能以直观的方式使用它们(例如 Chamber::pot 来自答案中的示例 ) ?

最佳答案

不,正如 Igor Tandetnik 在评论中指出的那样,非静态数据成员声明永远不是变量,因为它们永远不是对象。它们是为成员提供对象类型的声明,但在创建类的实例之前没有对象。

引用 Richard Smith :

I suppose the problem is in the ambiguity of what a "declaration of a reference" is. I believe the intent here is that a "declaration of a reference" is a declaration that declares a particular name to be of reference type (which a non-static data member declaration of reference type does), not necessarily a declaration that causes the lifetime of a particular reference to begin. Conversely, a "declaration of an object" is intended to be interpreted as a declaration that declares a particular name to name a specific object (which a non-static data member declaration does not).

That is:

  struct A {
int &a;
int b;
};

'a' is a declaration of a reference, and so we need another condition to restrict it from being a variable. 'b' is /not/ a declaration of an object, so we don't need to say anything further.

Suggestions on how to reword this to make it clearer would be welcome :)

这被跟进为 https://github.com/cplusplus/draft/issues/1280 , 发现了一些不一致之处。运气好的话,这将被视为同时清除标准的好机会。

关于c++ - 非静态非引用数据成员声明变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com