是否可以将forward-declared类的member函数声明为friend?我正在努力做以下事情:
class BigComplicatedClass; class Storage { int data_; public: int data() { return data_; } // OK,but provides too broad access: friend class BigComplicatedClass; // ERROR "invalid use of incomplete type": friend void BigComplicatedClass::ModifyStorage(); };
所以目标是(i)将朋友的声明限制在一个单一的方法中,(ii)不要包含复杂类的定义来减少编译时间.
// In Storage.h: class BigComplicatedClass_Helper; class Storage { // (...) friend class BigComplicatedClass_Helper; }; // In BigComplicatedClass.h: class BigComplicatedClass_Helper { static int &AccessData(Storage &storage) { return storage.data_; } friend void BigComplicatedClass::ModifyStorage(); };
然而,这似乎有点笨拙…所以我认为必须有一个更好的解决方案!
解决方法
正如@Ben所说,这是不可能的,但是您可以通过
“passkey”给该成员函数提供特定的访问.它有点像中间助手类,但是更清晰:
// Storage.h // forward declare the passkey class StorageDataKey; class Storage { int data_; public: int data() { return data_; } // only functions that can pass the key to this function have access // and get the data as a reference int& data(StorageDataKey const&){ return data_; } }; // BigComplicatedClass.cpp #include "BigComplicatedClass.h" #include "Storage.h" // define the passkey class StorageDataKey{ StorageDataKey(){} // default ctor private StorageDataKey(const StorageDataKey&){} // copy ctor private // grant access to one method friend void BigComplicatedClass::ModifyStorage(); }; void BigComplicatedClass::ModifyStorage(){ int& data = storage_.data(StorageDataKey()); // ... }