C++Primer读书笔记(1)-声明和定义

本文解析了C++中声明与定义的区别与联系,重点解释了如何通过extern关键字声明但不定义变量,以及变量定义与声明在程序中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近又捡起《C++ Primer》重读,随便将一些小知识点总结一下吧。


C++程序通常由许多文件组成,为了让多个文件访问相同的变量,c++区分了声明和定义


1.Declarations and Definitions

A defination of a variable allocates storage for the variable andmayalso specify an intial value for the variable.

There must be one and only one definition of variable in a program.

-->在一个程序中变量只能够被定义一次,变量的定义用于给变量分配储存空间,还可以为其指定初始值.

A declaration makes known the type and name of  the variable to the program.A Definition is also a declaration.When we define a variable,we declare its name

and type.We can declare a name without  defining it by  using the externkeyword.A declaration that is not also a definition consists of the object's name and 

its type preceded by the keyword extern.

->声明用于向程序表明变量的类型和名字。定义也是声明,当定义一个变量的时我们就已声明了它的类型和名字。可以通过使用extern关键字声明变量而不定义它。

不定义变量的声明包括对象名,对象类型,对象类型的关键字。

extern 声明不是定义,也不分配内存空间。

extern double pi=3.1416;//definition

extern double pi;//ok:declaration not definition

extern double pi=3.1416;//error:redefinition of pi




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值