Читаем C++. Сборник рецептов полностью

#include

#include // runtime_error

#include

#include


// Представляет ветеринара или дрессировщика

class Contact {

public:

 Contact() {}

 Contact(const std::string& name, const std::string& phone) :

  name_(name) {

  setPhone(phone);

 }

 std::string name() const { return name_; }

 std::string phone() const { return phone_; }

 void setName(const std::string& name) { name_ = name; }

 void setPhone(const std::string& phone) {

  using namespace std;

  using namespace boost;

  // Используйте Boost.Regex, чтобы убедиться, что телефон

  // задач в форме (ddd)ddd-dddd

  static regex pattern("\\([0-9]{3}\\)[0-9]{3}-[0-9]{4}");

  if (!regex_match(phone, pattern)) {

   throw runtime_error(string("bad phone number:") + phone);

  }

  phone_ = phone;

 }

private:

 std::string name_;

 std::string phone_;

};


// Сравнить на равенство два объекта класса Contact; используется в рецепте

// 14.9 (для полноты следует также определить operator!=)

bool operator--(const Contact& lhs, const Contact& rhs) {

 return lhs.name() == rhs.name() && lhs.phone() == rhs.phone();

}


// Записывает объект класса Contact в поток ostream

std::ostream& operator(std::ostream& out, const Contact& contact) {

 out << contact.name() << " " << contact.phone(); return out;

}


// Класс Animal представляет животное

class Animal {

public:

 // Конструктор по умолчанию класса Animal; этот конструктор будет вами

 // использоваться чаще всего Animal() {}

 // Конструирование объекта Animal с указанием свойств животного;

 // этот конструктор будет использован в рецепте 14.9

 Animal(const std::string& name,

  const std::string& species, const std::string& dob,

  const Contact& vet, const Contact& trainer) :

  name_(name), species_(species), vet_(vet), trainer_(trainer) {

   setDateOfBirth(dob)

  }

 // Функции доступа к свойствам животного

 std::string name() const { return name_; }

 std::string species() const { return species_; }

 boost::gregorian::date dateOfBirth() const { return dob_; )

 Contact veterinarian() const { return vet_; }

 Contact trainer() const { return trainer_; }


 // Функции задания свойств животного

 void setName(const std::string& name) { name_ = name; }

 void setSpecies(const std::string& species) { species_ = species; }

 void setDateOfBirth(const std::string& dob) {

  dob_ = boost::gregorian::from_string(dob);

 }

 void setVeterinarian(const Contact& vet) { vet_ = vet; }

 void setTrainer(const Contact& trainer) { trainer_ = trainer; }

private:

 std::string name_;

 std::string species_;

 boost::gregorian::date dob_;

 Contact vet_;

 Contact trainer_;

};


// Сравнение на равенство двух объектов Animal; используется в рецепте 14.9

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

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

1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных
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

Стивен Прата

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