Читаем Справочное руководство по C++ полностью

 int& elem(int i) { return v[i]; }

};

// 1.13

class vec: public vector {

 int low, high;

public:

 vec(int, int);

 int& elem(int);

 int& operator[](int);

};

main()

{

 vector a(10);

 for (int i=0; i‹a.size(); i++) {

  a[i] = i;

  cout ‹‹ a[i] ‹‹ " ";

 }

 cout ‹‹ "\n";

 vec b(10,19);

 for (i=0; i‹b.size(); i++) b[i+10] = a[i];

 for (i=0; i‹b.size(); i++) cout ‹‹ b[i+10] ‹‹ " ";

 cout ‹‹ "\n";

}

extern void exit(int);

// 1.13

void error(char* p)

{

 cerr ‹‹ p ‹‹ "\n";

 exit (1);

}

// 1.11

vector::vector(int s)

{

 if (s‹=0) error("bad vector size");

 sz = s;

 v = new int[s];

}

int& vector::operator[](int i)

{

 if (i‹0 || sz‹=i) error("vector index out of range");

 return v[i];

}

vector::~vector()

{

 delete v;

}

// 1.13

int& vec::elem(int i)

{

 return vector::elem(i-low);

}

vec::vec(int lb, int hb): (hb-lb+1)

{

 if (hb-lb‹0) hb = lb;

 low = lb;

 high = hb;

}

void vector::set_size(int) {/* dummy */}

int& vec::operator[](int i)

{

 if (i‹low || high‹i) error("vec index out of range");

 return elem(i);

}

<p>b1__14.cxx</p>

#include‹stream.hxx›

extern void exit(int);

extern void error(char*);

// 1.11

class vector {

 int *v;

 int sz;

public:

 vector(int); // constructor

 ~vector(); // destructor

 int size() { return sz; }

 void set_size(int);

 int& operator[](int);

 int& elem(int i) { return v[i]; }

};

vector::vector(int s)

{

 if (s‹=0) error("bad vector size");

 sz = s;

 v = new int[s];

}

int& vector::operator[](int i)

{

 if (i‹0 || sz‹=i) error("vector index out of range");

 return v[i];

}

vector::~vector()

{

 delete v;

}

// 1.14

class Vec: public vector {

public:

 Vec(int s): (s) {}

 Vec(Vec&);

 ~Vec() {}

 void operator=(Vec&);

 void operator*=(Vec&);

 void operator*=(int);

};

Vec::Vec(Vec& a): (a.size())

{

 int sz = a.size();

 for (int i = 0; i‹sz; i++) elem(i) =a.elem(i);

}

void Vec::operator=(Vec& a)

{

 int s = size();

 if (s != a.size()) error("bad vector size for =");

 for (int i =0; i‹s; i++) elem(i)=a.elem(i);

}

Vec operator+(Vec& a, Vec& b)

{

 int s = a.size();

 if (s!= b.size()) error("bad vector size for +");

 Vec sum(s);

 for (int i=0; i‹s; i++)

 sum.elem(i) = a.elem(i) + b.elem(i);

 return sum;

}

void error(char* p)

{

 cerr ‹‹ p ‹‹ "\n";

 exit (1);

}

void vector::set_size(int) {}

main()

{

 Vec a(10);

 Vec b(10);

 for (int i=0; i‹a.size(); i++) a[i] = i;

 b = a;

 Vec c = a+b;

 for (i=0; i‹c.size(); i++) cout ‹‹ c[i] ‹‹ "\n";

}

<p>b1__16.cxx</p>

#include ‹vector.hxx›

declare(vector,int);

implement(vector,int);

main()

{

 vector(int) vv(10);

 vv[2] = 3;

 vv[10] = 4; // range error

}

<p>b2_1_3.cxx</p>

#include ‹stream.hxx›

int a = 1;

void f()

{

 int b = 1;

 static int c = 1;

 cout ‹‹ " a = " ‹‹ a++

  ‹‹ " b = " ‹‹ b++

  ‹‹ " c = " ‹‹ c++ ‹‹ "\n";

}

main ()

{

 while (a ‹ 4) f();

}

<p>b2_3.cxx</p>

#include ‹stream.hxx›

main()

{

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных
Adobe Flash. Создание аркад, головоломок и других игр с помощью ActionScript
Adobe Flash. Создание аркад, головоломок и других игр с помощью ActionScript

Данная книга посвящена программированию игр с помощью ActionScript. Здесь вы найдете подробные указания, необходимые для создания самых разных игр – аркад, головоломок, загадок и даже игровых автоматов. В тексте приведены исходные коды программ и детальные, доступно изложенные инструкции. Базовые принципы программирования ActionScript рассматриваются на примере игр, однако вы без труда сможете применить полученные знания и для разработки неигровых проектов, таких как Web-дизайн и реклама. Рекомендации Гэри Розенцвейга помогут вам не только придумывать занимательные игры и размещать их на Web-сайте, но и оптимизировать скорость их работы, а также защищать свои творения от несанкционированного копирования. Представленный в книге код несложно изменить для использования в других программах.Книга предназначена для широкого круга читателей – создателей анимационных роликов, художников-оформителей, программистов и разработчиков Web-сайтов. Издание может также выступать в качестве практического пособия по изучению ActionScript.

Гэри Розенцвейг

Программирование, программы, базы данных / Программирование / Книги по IT