gpt4 book ai didi

c++ - 变量的声明、定义和初始化有什么区别?

转载 作者:行者123 更新时间:2023-12-01 23:13:21 24 4
gpt4 key购买 nike

阅读 question 后,我知道声明和定义之间的区别。那么这是否意味着定义等于声明加上初始化?

最佳答案

声明

声明,一般是指在程序中引入一个新的名称。例如,您可以通过描述它的“签名”来声明一个新函数:

void xyz();

或者声明一个不完整的类型:

class klass;
struct ztruct;

最后但并非最不重要的一点是,声明一个对象:

int x;

在 C++ 标准第 §3.1/1 中,它被描述为:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

定义

定义是先前声明的名称的定义(或者它可以是定义和声明)。例如:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

具体而言,C++ 标准在第 §3.1/1 中将其定义为:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

初始化

初始化是指在构造时对值进行“赋值”。对于 T 类型的通用对象,它通常采用以下形式:

T x = i;

但在 C++ 中它可以是:

T x(i);

甚至:

T x {i};

使用 C++11。

结论

So does it mean definition equals declaration plus initialization?

这要看情况。关于你在说什么。如果您正在谈论一个对象,例如:

int x;

这是一个没有初始化的定义。相反,以下是带有初始化的定义:

int x = 0;

在某些上下文中,谈论“初始化”、“定义”和“声明”是没有意义的。例如,如果您正在谈论一个函数,初始化并没有多大意义。

所以,答案是:定义并不自动意味着声明加初始化。

关于c++ - 变量的声明、定义和初始化有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58364310/

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