Chinaunix首页 | 论坛 | 博客
  • 博客访问: 271459
  • 博文数量: 55
  • 博客积分: 2030
  • 博客等级: 大尉
  • 技术积分: 737
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-13 18:06
文章分类

全部博文(55)

文章存档

2011年(2)

2010年(7)

2009年(17)

2008年(29)

我的朋友

分类: C/C++

2008-09-07 17:07:20

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) |
    给主人留下些什么吧!~~