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

📄 smartarray.cpp

📁 Thinking in C++ 2nd edition source code which are all the cores of the book Thinking in C++ second e
💻 CPP
字号:
//: C03:SmartArray.cpp
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// An array which checks boundaries
#include <iostream>
#include <cstdlib> // For exit() declaration
using namespace std;

class Array {
  enum { size = 10 };
  int a[size];
  void check_index(const int index); // Private function
public:
  Array(const int initval = 0); // Default argument value
  void setval(const int index, const int value);
  int readval(const int index);
};
// Constructor (don't duplicate the default value!):
Array::Array(const int intval) {
  for (int i = 0; i < size; i++)
    setval(i, intval);  // Call another member function
}
void Array::check_index(const int index) {
  if(index < 0 || index >= size) { // Logical OR
    cerr << "Array error: setval index out of bounds" << endl;
    exit(1);  // Standard C library function; quits program
  }
}
void Array::setval(const int index, const int value) {
  check_index(index);
  a[index] = value;
}
int Array::readval(const int index) {
  check_index(index);
  return a[index];
}
int main() {
  Array A, B(47);
  // Out of bounds -- see what happens
  int x = B.readval(10); 
} ///:~

⌨️ 快捷键说明

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