⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 constpointers.cpp

📁 ThinkingC++中文版
💻 CPP
字号:
//: C08:ConstPointers.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;

void main()
{
	int d = 1;
	const int e = -1;

	int* pointer;
	const int* pointer_to_const;  //常量指针pointer_to_const is a pointer, which points to a const int
	//int const* pointer_to_const;	//与上述等价
	
	pointer = &d;//ok
    *pointer = -1;
	//pointer = &e;//not ok,you can’t assign the address of a const object to a non-const pointer because then you’re saying you might change the object via the pointer. 
	//pointer = (int*)&e;//ok,程序员自己打破由const提供的安全机制,编译器就无能为力!
  
	pointer_to_const = &e;
	pointer_to_const = &d;//ok,	You can assign the address of a non-const object to a const pointer because you’re simply promising not to change something that is OK to change.
 
	//* pointer_to_const = 99999;//not ok

	int* const const_pointer = &d;	//指针常量w is a pointer, which is const, that points to an int.  当场初始化
	//int* const const_pointer = &e;  //错
	*const_pointer = 1; 


	const int* const x = &d;  // (1)   const pointer points to a const object 
	int const* const x2 = &e; // (2) 与 (1)等价

	//Legal but bad practice
	pointer = (int*)&e;
	*pointer = 1;//发现常量对象e的值已改变.Although C++ helps prevent errors it does not protect you from yourself if you want to break the safety mechanisms.


} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -