【问题标题】:Friend function in class defined in namespace命名空间中定义的类中的友元函数
【发布时间】:2020-09-19 12:42:15
【问题描述】:

我正在尝试在DataBase.h 文件中声明的DataBase 命名空间中创建一个函数,该函数在DataBase.cpp 中实现,需要访问Collection 类的受保护成员。

这是我目前拥有的

Collection.h:

class Collection
{
   ...
protected:
   string name;
   friend Collection& DataBase::getCollection(string name);
};

DataBase.h:

namespace DataBase {
    ...
    Collection& getCollection(std::string collectionName);
}

DataBase.cpp:

namespace DataBase {
    ...
    Collection& getCollection(std::string collectionName)
    {
        for (auto& collection : _collections)
            if(collection.name == collectionName)
            {
               ...
            }
    }

}

问题是我无法访问 name 属性。

【问题讨论】:

  • 不,朋友类/函数应该能够访问甚至私有成员。
  • DataBase::getCollection() 使用类Collection 的成员(如collection.name),因此该类的定义需要在此之前对编译器可见。

标签: c++ class namespaces friend


【解决方案1】:

您必须转发声明包含命名空间的友元函数。我不知道您如何使用_collections,所以我稍微更改了示例并将所有内容放在一个文件中以开始使用。

#include <string>
#include <vector>
using namespace std;

class Collection;

namespace DataBase {  
    Collection* getCollection(std::vector<Collection>& collections, std::string collectionName);
}

class Collection
{
protected:
  string name;
  friend Collection* DataBase::getCollection(std::vector<Collection>& collections, std::string name);
};


namespace DataBase {
  Collection* getCollection(std::vector<Collection>& collections, std::string collectionName)
  {
    for (auto& collection : collections)
      if (collection.name == collectionName)
      {
        return &collection;
      }
    return nullptr;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2012-06-11
    • 2013-05-19
    • 1970-01-01
    • 2014-08-12
    • 2016-12-12
    • 1970-01-01
    相关资源
    最近更新 更多