Exceptional C++

【Exceptional C++(14)】编译期的依赖性

2018-01-29  本文已影响14人  downdemo

问题

// gotw007.h
#include "a.h" // class A
#include "b.h" // class B
#include "c.h" // class C
#include "d.h" // class D
    // 只有A和C有虚函数
#include <iostream>
#include <ostream>
#include <sstream>
#include <list>
#include <string>
class X : public A {
public:
    X(const C&);
    D Function1(int, char*);
    D Function1(int, C);
    B& Function2(B);
    void Function3(std::ostream&) const;
    std::ostream& print(std::ostream&) const;
private:
    std::string name_;
    std::list<C> clist_;
    D d_;
};
std::ostream& operator<<(std::ostream& os, const X& x)
{ return x.print(os); }
class Y : private B {
public:
    C Function4(A);
private:
    std::list<std::wostringstream*> alist_;
};

解答

//x.h
#include "a.h"
#include <iosfwd>
class C;
class D;
class X : public A {
public:
    X(const C&);
    D Function1(int, char*);
    D Function1(int, C);
    B& Function2(B);
    void Function3(std::wostringstream&);
    std::ostream& print(std::ostream&) const;
private:
    class XImpl* pimpl_;
};
inline std::ostream& operator<<(std::ostream&os, const X& x)
{ return x.print(os); }
// y.h,没有#include
class A;
class C;
class Y {
public:
    C Function4(A);
private:
    class TImpl* pimpl_;
};
// gotw007.h作为存根包含两个#include
// 通过x.h又附带了另外两个
#include "x.h"
#include "y.h"
// gotw007.cpp中的新结构
// impl对象应该在X和Y的构造函数中用new创建
// 并在X和Y的析构函数中用delete清除
// X和Y的成员函数要通过pimpl_指针访问数据
struct XImpl
{
    std::string name_;
    std::list<C> clist_;
    D d_;
};
struct YImpl
{
    std::list<std::wostringstream*> alist_;
    B b_;
};
// 现在,X和Y的使用者只要包含a.h和iosfwd
// 即使后来更新代码需要包含y.h并去掉gotw007.h
// 也不用加一行#include
上一篇下一篇

猜你喜欢

热点阅读