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 には興味深い提案があります。このような変数を多数公開する必要がある場合は、それらをすべて 1 つのクラスに配置することをお勧めします。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);
}