c – 将forward声明的类的成员函数声明为friend

前端之家收集整理的这篇文章主要介绍了c – 将forward声明的类的成员函数声明为friend前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以将forward-declared类的member函数声明为friend?我正在努力做以下事情:
  1. class BigComplicatedClass;
  2.  
  3. class Storage {
  4. int data_;
  5. public:
  6. int data() { return data_; }
  7. // OK,but provides too broad access:
  8. friend class BigComplicatedClass;
  9. // ERROR "invalid use of incomplete type":
  10. friend void BigComplicatedClass::ModifyStorage();
  11. };

所以目标是(i)将朋友的声明限制在一个单一的方法中,(ii)不要包含复杂类的定义来减少编译时间.

一种方法可能是添加一个充当中介的类:

  1. // In Storage.h:
  2. class BigComplicatedClass_Helper;
  3. class Storage {
  4. // (...)
  5. friend class BigComplicatedClass_Helper;
  6. };
  7.  
  8. // In BigComplicatedClass.h:
  9. class BigComplicatedClass_Helper {
  10. static int &AccessData(Storage &storage) { return storage.data_; }
  11. friend void BigComplicatedClass::ModifyStorage();
  12. };

然而,这似乎有点笨拙…所以我认为必须有一个更好的解决方案!

解决方法

正如@Ben所说,这是不可能的,但是您可以通过 “passkey”给该成员函数提供特定的访问.它有点像中间助手类,但是更清晰:
  1. // Storage.h
  2. // forward declare the passkey
  3. class StorageDataKey;
  4.  
  5. class Storage {
  6. int data_;
  7. public:
  8. int data() { return data_; }
  9. // only functions that can pass the key to this function have access
  10. // and get the data as a reference
  11. int& data(StorageDataKey const&){ return data_; }
  12. };
  13.  
  14. // BigComplicatedClass.cpp
  15. #include "BigComplicatedClass.h"
  16. #include "Storage.h"
  17.  
  18. // define the passkey
  19. class StorageDataKey{
  20. StorageDataKey(){} // default ctor private
  21. StorageDataKey(const StorageDataKey&){} // copy ctor private
  22.  
  23. // grant access to one method
  24. friend void BigComplicatedClass::ModifyStorage();
  25. };
  26.  
  27. void BigComplicatedClass::ModifyStorage(){
  28. int& data = storage_.data(StorageDataKey());
  29. // ...
  30. }

猜你在找的C&C++相关文章