2

クラスを仮定します: Library

そして、基本クラス LibraryCustomer からの派生クラスのグループがあります。たとえば、Kid、Parent、Student などです。

Library のクラスには、(大量の) プライベート メンバー変数のグループがあります。ライブラリのクラスにはたくさんのプライベート メンバーが存在するため、面倒な getter と setter は使用したくありません。さらに、LibraryCustomer 派生クラスは、これらのメンバーを参照することがよくあります。Getter と Setter は便利ではありません。

これらの LibraryCustomers が Library のプライベート メンバーにアクセスできるようにするには、それらの LibraryCustomers を Library のフレンド クラスとして要求する必要があります。

しかし、派生クラスは増え続けるため、クラス ライブラリにそれらを 1 つずつ追加したくありません。

Library の友人として基本クラス LibraryCustomer を追加すると機能しないようです。では、別のより良い方法は何ですか?

【追記】Libraryのクラスでたくさんのprivateメンバー変数にアクセスしたいです。ゲッター、セッターは多いので使いたくない。LibraryCustomer から派生したクラスが、Library のクラスのプライベート メンバー変数に自由にアクセスできることを願っています。

4

1 に答える 1

1

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);
}
于 2015-05-06T20:59:38.917 に答える