相依于声明式,不要相依于定义式
- 定义某类型的references和pointer,只需用到该类型的声明式
- 定义某类型的objects,就需要用到该类型的定义式
- 当声明一个函数而它用到某个类,或者该函数以by value方式传递该类的参数(返回值)时,不需要该类的定义式
class Person
{
public:
Person(const std::string& name, const Date& birthday,
const Address& addr);
std::string name()const;
private:
std::string theName; //实现细目
Date theBirthDate; //实现细目
Address theAddress; //实现细目
};
{
public:
Person(const std::string& name, const Date& birthday,
const Address& addr);
std::string name()const;
private:
std::string theName; //实现细目
Date theBirthDate; //实现细目
Address theAddress; //实现细目
};
handle classes
- 将接口从实现中分离,可以将对象实现细目隐藏于一个指针背后,将Person分割为两个类,这样的Person类一般称为Handle classes:
//接口类Person.h
#include<string>
#include<memory>
class PersonImpl; //Person实现类的前置声明
class Date; //Person接口用到的classes的前置声明
class Address;
class Person
{
public:
Person(const std::string& name, const Date& birthday,
const Address& addr);
std::string name()const;
void clearAppointments(Date d);
private:
std::tr1::shared_ptr<PersonImpl> pImpl;//指针,指向其实现物
};
#include<string>
#include<memory>
class PersonImpl; //Person实现类的前置声明
class Date; //Person接口用到的classes的前置声明
class Address;
class Person
{
public:
Person(const std::string& name, const Date& birthday,
const Address& addr);
std::string name()const;
void clearAppointments(Date d);
private:
std::tr1::shared_ptr<PersonImpl> pImpl;//指针,指向其实现物
};
//实现类PersonImpI.h
#include "Person.h"
#include "Date.h"
#include "Address.h"
class PersonImpl
{
public:
public:
PersonImpl(const std::string& name, const Date& birthday,
const Address& addr);
std::string name()const;
void clearAppointments(Date d);
private:
std::string theName; //实现细目
Date theBirthDate; //实现细目
Address theAddress; //实现细目
};
interface classes
将Person类设计为abstract base class,称为interface class。只提供函数接口,不实现成员变量,相当于java和C#的interface。不过c++中更为灵活。