【发布时间】: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