提供一个函数LibraryCustomer
来访问Library
以获取数据并将该数据提供给从LibraryCustomer
.
class Library
{
friend class LibraryCustomer;
private:
std::string name;
};
class LibraryCustomer
{
protected:
std::string getLibraryName(Library const& lib)
{
return lib.name;
}
};
class Kid : public LibraryCustomer
{
// Can use LibraryCustomer::getLibraryName() any where
// it needs to.
};
Library
话虽如此,从自身提供对数据的访问会更容易。
class Library
{
public:
std::string getName() const { return name; }
private:
std::string name;
};
然后,就不需要friend
声明和包装函数了LibraryCustomer::getLibraryName()
。
编辑
@MooingDuck 有有趣的建议。如果您必须公开许多此类变量,最好将它们全部放在一个类中。http://coliru.stacked-crooked.com/a/2d647c3d290604e9上的工作代码。
#include <iostream>
#include <string>
class LibraryInterface {
public:
std::string name;
std::string name1;
std::string name2;
std::string name3;
std::string name4;
std::string name5;
std::string name6;
};
class Library : private LibraryInterface
{
public:
Library() {name="BOB";}
private:
LibraryInterface* getLibraryInterface() {return this;} //only LibraryCustomer can aquire the interface pointer
friend class LibraryCustomer;
};
class LibraryCustomer
{
protected:
LibraryInterface* getLibraryInterface(Library& lib) {return lib.getLibraryInterface();} //only things deriving from LibraryCustomer can aquire the interface pointer
};
class Kid : public LibraryCustomer
{
public:
void function(Library& lib) {
LibraryInterface* interface = getLibraryInterface(lib);
std::cout << interface->name;
}
};
int main() {
Library lib;
Kid k;
k.function(lib);
}