[英]Friend function in class defined in namespace
我正在嘗試在DataBase.h
文件中聲明的DataBase.cpp
DataBase
實現需要訪問Collection
class 的受保護成員。
這是我目前擁有的
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 屬性。
您必須轉發聲明朋友 function 包括命名空間。 我不知道您是如何使用_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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.