C++编程思想 第1卷 第8章 常量 函数参数和返回值 传递和返回地址

如果传递或返回一个地址 一个指针或一个引用,客户程序员去取地址并
修改初值是可能的。

如果指针或引用成为const,就会阻止这类事的发生
无论什么时候传递一个地址给一个函数,都应该尽可能用const修饰它

时候选择返回一个指向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
} ///:~

函数t()把一个普通的非const指针作为一个参数
而函数u()把一个const指针作为参数

函数v()和w()测试返回值的语义
w()返回值要求这个指针及这个指针说指向的对象均为常量

在main()中,函数被各种参数测试

函数v()的返回值只可以被赋给一个const指针

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81151520
今日推荐