设为首页 加入收藏

TOP

2.2 Variables (1)
2013-10-07 16:15:17 来源: 作者: 【 】 浏览:81
Tags:2.2 Variables

A variable provides us with named storage that our programs can manipulate. Each variable in C++(www.cppentry.com) has a type. The type determines the size and layout of the variable’s memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable. C++(www.cppentry.com) programmers tend to refer to variables as “variables” or “objects” interchangeably.

2.2.1 Variable Definitions

A simple variable definition consists of a type specifier, followed by a list of one or more variable names separated by commas, and ends with a semicolon. Each name in the list has the type defined by the type specifier. A definition may (optionally) provide an initial value for one or more of the names it defines:

  1. int sum = 0, value, // sum, value, and units_sold have type int   
  2. units_sold = 0; // sum and units_sold have initial value 0   
  3. Sales_item item; // item has type Sales_item (see § 1.5.1 (p. 20))   
  4. // string is a library type, representing a variable-length sequence of characters   
  5. std::string book("0-201-78345-X"); // book initialized from string literal  

The definition of book uses the std::string library type. Like iostream (§ 1.2, p. 7), string is defined in namespace std. We’ll have more to say about the string type in Chapter 3. For now, what’s useful to know is that a string is a type that represents a variable-length sequence of characters. The string library gives us several ways to initialize string objects. One of these ways is as a copy of a string literal (§ 2.1.3, p. 39). Thus, book is initialized to hold the characters 0-201-78345-X.

TERMINOLOGY: WHAT IS AN OBJECT

C++(www.cppentry.com) programmers tend to be cavalier in their use of the term object. Most generally, an object is a region of memory that can contain data and has a type.

Some use the term object only to refer to variables or values of class types. Others distinguish between named and unnamed objects, using the term variable to refer to named objects. Still others distinguish between objects and values, using the term object for data that can be changed by the program and the term value for data that are read-only.

In this book,we’ll follow the more general usage that an object is a region ofmemory that has a type. We will freely use the term object regardless of whether the object has built-in or class type, is named or unnamed, or can be read or written.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.1 Primitive Built-in Types (7) 下一篇2.2 Variables (2)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·数据库:推荐几款 Re (2025-12-25 12:17:11)
·如何最简单、通俗地 (2025-12-25 12:17:09)
·什么是Redis?为什么 (2025-12-25 12:17:06)
·对于一个想入坑Linux (2025-12-25 11:49:07)
·Linux 怎么读? (2025-12-25 11:49:04)