标准输入输出
1 |
|
cin(see-in):标准输入
1
2
3// 输入v1的值
int v1 = 0;
std::cin >> v1;cout(see-out):标准输出
1
2// 输出字符串"Enter two numbers:"
std::cout << "Enter two numbers:" << std::endl;命名空间(namespace)
命名空间的出现是为了避免如下的问题:
我们声明了同名函数dance
,那么如何调用指定的某个函数呢?
1 |
|
使用命名空间,指定调用的函数:
1 | int main() { |
引用(References)
引用就是一个对象的别名
A reference is not an object. Instead, a reference is just another name for an already existing object.
1 |
|
- 引用必须初始化
- 一旦初始化,不可以再将引用指向其他对象
1 | int &refVal4 = 10; // error: initializer must be an object |
Exercises Section 2.3.1
Exercise 2.15: Which of the following definitions, if any, are invalid? Why?
(a) int ival = 1.01;
(b) int &rval1 = 1.01;
(c) int &rval2 = ival;
(d) int &rval3;
(a) ✅(b)❌ 初始化赋值必须是int对象
(c) ✅ (d)❌ 引用必须被初始化
指针(Pointers)
1 | int *ip1, *ip2; // both ip1 and ip2 are pointers to int |
- 与引用不同,指针本身就是一个对象
- 在指针的生命周期中,可以指向不同的对象
1 | int ival = 42; |
- 指针存放的值是另一个对象的地址
1 | double dval; |
- 指针类型必须和其指向的地址中存放的对象的类型相同
注:& 和 * 有多种含义
&、*可以当做声明使用,比如:
1
2
3
4 int i = 42;
int&r=i; //& *followsatypeandispartofadeclaration; r is a *reference*
int *p; // * *follows a type and is part of a declaration; p is a *pointer*&也可以作取地址符使用:
1 p = &i; // & is used in an expression as the address-of operator.*可以作取值符号使用:
1
2 *p = i; // * is used in an expression as the dereference operator
int &r2 = *p; // & is part of the declaration; * is the dereference operator
使用指针访问一个对象
1
2
3int ival = 42;
int *p = &ival; // p holds the address of ival; p is a pointer to ival
cout << *p; // * yields the object to which p points; prints 42使用指针指向空指针(Null Pointers)
1
2
3
4int *p1 = nullptr; // equivalent to int *p1 = 0;
int *p2 = 0; // directly initializes p2 from the literal constant 0
// must #include cstdlib
int *p3 = NULL; // equivalent to int *p3 = 0;
void指针(void* Pointers)
void指针能够指向任意类型的对象
1 | double obj = 3.14, *pd = &obj; |
Exercise 2.20: What does the following program do?
int i = 42;
int *p1 = &i;*p1 = *p1 * *p1;
*p1 = 42 * 42