我想在 DataBase
中声明的命名空间。DataBase.h
文件,并在 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)
{
...
}
}
}
问题是我不能访问名称属性。
你必须向前声明朋友函数,包括命名空间。我不知道你是如何使用 _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;
}
}