hide the object implementation behind a pointer
#include <string> // standard library components #include <memory> // for tr1::shared_ptr; see below
class PersonImpl; // forward decl of Person impl. class class Date; // forward decls of classes used in class Address; // Person interface
class Person {
public: Person(const std::string& name, const Date& birthday, const Address& addr); std::string name() const; std::string birthDate() const; std::string address() const; ...
private: // ptr to implementation;
std::tr1::shared_ptr<PersonImpl> pImpl; // see Item 13 for info on }; // std::tr1::shared_ptr
|
never need a class definition to declare a function using that class, not even if the function passes or returns the class type by value:
class Date; // class declaration
Date today(); // fine — no definition void clearAppointments(Date d); // of Date is needed
|
header files need to come in pairs: one for declarations, the other for definitions
contains declarations of iostream components whose corresponding definitions are in several different headers, including , , , and .
Clients of an Interface class must have a way to create new objects. They typically do it by calling a function that plays the role of the constructor for the derived classes that are actually instantiated. Such functions are typically called factory functions
class Person { public: ... static std::tr1::shared_ptr<Person> // return a tr1::shared_ptr to a new create(const std::string& name, // Person initialized with the const Date& birthday, // given params; see Item 18 for const Address& addr); // why a tr1::shared_ptr is returned ... };
std::string name; Date dateOfBirth; Address address; ... // create an object supporting the Person interface std::tr1::shared_ptr<Person> pp(Person::create(name, dateOfBirth, address));
|
RealPerson demonstrates one of the two most common mechanisms for implementing an Interface class: it inherits its interface specification from the Interface class (Person), then it implements the functions in the interface. A second way to implement an Interface class involves multiple inheritance
The general idea behind minimizing compilation dependencies is to depend on declarations instead of definitions. Two approaches based on this idea are Handle classes and Interface classes.
Library header files should exist in full and declaration-only forms. This applies regardless of whether templates are involved.
阅读(768) | 评论(0) | 转发(0) |