cout ‹‹ "echo: " ‹‹ x ‹‹ "\n";

 return s;

}

void error(char* p)

{

 cout ‹‹ p ‹‹ "\n";

 exit(1);

}

char& string::operator[](int i)

{

 if (i‹0 || strlen(p-›s)‹i) error("index out of range");

 return p-›s[i];

}

main()

{

 string x[100];

 int n;

 cout ‹‹ "here we go\n";

 for (n = 0; cin››x[n]; n++) {

  string y;

  if (n==100) error("too many strings");

  cout ‹‹ (y = x[n]);

  if (y=="done") break;

 }

 cout ‹‹ "here we go back again\n";

 for (int i=n-1; 0‹=i; i--) cout ‹‹ x[i];

}

<p>b7_2_8.cxx</p>

#include ‹stream.hxx›

struct employee {

 friend class manager;

 employee* next;

 char* name;

 short department;

 virtual void print();

};

struct manager: employee {

 employee* group;

 short level;

 void print();

};

void employee::print()

{

 cout ‹‹ name ‹‹ "\t" ‹‹ department ‹‹ "\n";

}

void manager::print()

{

 employee::print();

 cout ‹‹ "\tlevel " ‹‹ level ‹‹ "\n";

}

void f(employee* ll)

{

 for (; ll; ll=ll-›next) ll-›print();

}

main ()

{

 employee e;

 e.name = "J. Brown";

 e.department = 1234;

 e.next = 0;

 manager m;

 m.name = "J. Smith";

 m.department = 1234;

 m.level = 2;

 m.next = &e

 f(&m);

}

<p>b7_7.cxx</p>

#include ‹stream.hxx›

struct base { base(); };

struct derived: base { derived(); };

base:: base()

{

 cout ‹‹ "\tbase 1: this=" ‹‹ long(this) ‹‹ "\n";

 if (this == 0) this = (base*)27;

 cout ‹‹ "\tbase 2: this=" ‹‹ long(this) ‹‹ "\n";

}

derived::derived()

{

 cout ‹‹ "\tderived 1: this=" ‹‹ long(this) ‹‹ "\n";

 if (this == 0) this = (derived*)43;

 cout ‹‹ "\tderived 2: this=" ‹‹ long(this) ‹‹ "\n";

}

main()

{

 cout ‹‹ "base b;\n";

 base b;

 cout ‹‹ "new base;\n";

 new base;

 cout ‹‹ "derived d;\n";

 derived d;

 cout ‹‹ "new derived;\n";

 new derived;

 cout ‹‹ "new derived;\n";

 new derived;

 cout ‹‹ "at the end\n";

}

<p>b8_3_3.cxx</p>

#include ‹xstream.hxx›

extern void exit(int);

void error(char* s, char* s2)

{

 cerr ‹‹ s ‹‹ " " ‹‹ s2 ‹‹ "\n";

 exit(1);

}

main(int argc, char* argv[])

{

 if (argc != 3) error ("wrong number of arguments",");

 filebuf f1;

 if (f1.open(argv[1],input) == 0)

  error("cannot open input file",argv[1]);

 istream from(&f1);

 filebuf f2;

 if (f2.open(argv[2],output) == 0)

  error("cannot open input file",argv[2]);

 ostream to(&f2);

 char ch;

 while (from.get(ch)) to.put(ch);

 if (!from.eof() || to.bad())

  error("something strange happened",");

}

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

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