constpointer.cpp

来自「ThinkingC++中文版」· C++ 代码 · 共 55 行

CPP
55
字号
//: 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;
}

void main() 
{
  int* b;
  double* r;
  void* v;
  v = r;
  b = (int*)v;	 //


  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
//!  *v()='1';
//  int* ip2 = w(); // Not OK
  const int* const ccip = w(); // OK
  const int* cip2 = w(); // OK
//!  *w() = 1; // Not OK
} ///:~

⌨️ 快捷键说明

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