C++编程思想 第1卷 第8章 常量 指针 const指针

指针也可以const

指针是指向int的const指针,指针本身是const指针,编译器要求初始值
值在指针生命周期内不变

//: C08:ConstPointer.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Constant pointer arg/return

void t(int*) {}

void u(const int* cip) {
//!  *cip = 2; // Illegal -- modifies value
  int i = *cip; // OK -- copies value
//!  int* ip2 = cip; // Illegal: non-const
}

const char* v() {
  // Returns address of static character array:
  return "result of function v()";
}

const int* const w() {
  static int i;
  return &i;
}

int main() {
  int x = 0;
  int* ip = &x;
  const int* cip = &x;
  t(ip);  // OK
//!  t(cip); // Not OK
  u(ip);  // OK
  u(cip); // Also OK
//!  char* cp = v(); // Not OK
  const char* ccp = v(); // OK
//!  int* ip2 = w(); // Not OK
  const int* const ccip = w(); // OK
  const int* cip2 = w(); // OK
//!  *w() = 1; // Not OK
} ///:~

int* ip = &x;
int* 本身是一个离散类型
* 与标识符结合,而不是与类型结合
它可以被放在类型名和标识符的任何地方
  

无输出

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81148209