請注意,在頭文件中公開實現細節可能具有優勢,以及在細節更改時強制重新編譯的缺點;函數可以更容易內聯,這可以提高運行時性能。您需要決定何時何地進行折衷是值得的。
通過引入額外的間接級別,可以隱藏源文件中的所有私有實現細節。一種常見的方法是將指針到私人的實現(或「平普爾」)成語,例如:
// Header file
class Thing {
public:
Thing(...);
~Thing();
// Public interface
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
// Source file
struct Thing::Impl {
// private details
};
Thing(...) : impl(new Impl(...)) {}
~Thing() {}
// Implementation of public interface
另一種可能性是定義一個抽象的接口,具有一個或多個工廠創建包含具體實例實現,例如:
// Header file
class Thing {
public:
virtual ~Thing() {}
static std::unique_ptr<Thing> make(...);
// Pure virtual public interface
};
// Source file
class ThingImpl : public Thing {
// Implementation of public interface
// Private implementation details
};
std::unique_ptr<Thing> Thing::make(...) {
return std::unique_ptr<Thing>(new ThingImpl(...));
}
這些方法都將所有的實現細節源文件中,所以這是一個需要在細節改變重新編譯的唯一的事情。但是都會引入額外的指針間接和/或間接的函數調用,這可能會影響運行時性能。
您的問題不清楚,但您可能正在尋找[pimpl idiom](http://www.gotw.ca/publications/mill04.htm)。 – 2013-02-27 12:41:12