c++ - C++中对象和变量的区别

标签 c++ object variables language-lawyer

我正在使用列出的书籍学习 C++ here .我的问题是变量和对象之间有区别吗?考虑以下示例:

int i = 0; //i is an object of type int. Or we can say i is a variable of type int
int &refI = i; //refI is a "reference variable" of "reference type `int&`. But here refI is not an object. 

我目前的理解是,变量和对象这两个术语在很大程度上是重叠的。但在某些情况下,例如上面的 refI,可能会有一些差异。特别地,refI引用类型int& 的引用变量,而refI 不是对象,因为引用是一些其他对象的别名。而 i 既是一个对象又是一个变量。

我的问题是我是否正确分析了上面的 refI 案例?如果不是,标准对此有何规定。

我的第二个问题是,标准 C++ 是否严格区分这两个术语。如果是,如何以及在哪里。例如,

a variable may be defined as an object with a name. And any object without a name is not a variable.

Here用户说变量和对象不同。

编辑

我问这个问题也是因为我知道在 Python 中(因为它是一种动态类型的语言)变量和对象之间有明显的区别。 C++标准是否也做出了如此明确的区分。

最佳答案

Difference between an object and a variable in C++

变量是一个编程语言级别的概念。一个变量有一个类型并且它(通常)有一个名字。变量可以表示对象或引用。

标准中没有关于“变量”含义的简明定义,也没有单独专门介绍它们的部分,但最接近指定其含义的单独规则是:

[basic.pre]

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.


对象是语言定义的抽象机器层次上的一个概念。它主要在开始的“对象模型 [intro.object]”部分中指定:

[intro.object]

The constructs in a C++ program create, destroy, refer to, access, and manipulate objects. An object is created by a definition, by a new-expression ([expr.new]), by an operation that implicitly creates objects (see below), when implicitly changing the active member of a union, or when a temporary object is created ([conv.rval], [class.temporary]). An object occupies a region of storage in its period of construction ([class.cdtor]), throughout its lifetime, and in its period of destruction ([class.cdtor]).


 int i = 0; //i is an object of type int. Or we can say i is a variable of type int

iint 类型的变量。变量的名称表示一个对象。

int &refI = i; //refI is a "reference variable" of "reference type `int&`. But here refI is not an object. 

refIint& 类型的变量。变量的名称表示引用。引用绑定(bind)到由 i 命名的对象,可以看作是同一对象的另一个名称。

关于c++ - C++中对象和变量的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71531033/

相关文章:

c++ - 为什么 C++ 中的模板 mixin 不再是主流?

c++ - 如何在 Visual Studio 2015 中更新我的 C++ 项目以使用新的通用 CRT?

java - 使用字符串变量Android创建对象的最佳方法

c++ - C++中,为什么返回不同对象私有(private)变量的指针会导致段错误?

PHP:将对象用作数据库产品的有效方法

javascript - 如何在 javascript 代码中传递带有 url 的变量?

javascript - 使用循环将多个数组组合成一个对象

java - 变量类型与值类型相同吗?

c++ - 关于 std::array fill 的设计决策

c++ - 带有 ESP8266 和 C++ 代码的 Arduino