2

假设一个类:图书馆

而我们有一组从基类LibraryCustomer派生的类,如:Kid、Parent、Student等

在 Library 类中,有一组(大量)私有成员变量。由于 Library 类中有大量私有成员,我不想使用乏味的 getter 和 setter。此外,LibraryCustomer 派生类通常会引用这些成员。Getter 和 Setter 不方便。

为了让这些 LibraryCustomers 访问 Library 中的那些私有成员,我需要将这些 LibraryCustomers 声明为 Library 中的朋友类。

但是由于派生类不断增长,我不想在类库中一一添加。

在 Library 中添加基类 LibraryCustomer 作为朋友似乎不起作用。那么还有什么更好的方法呢?

[更新] 我想访问库类中的大量私有成员变量。由于有很多,所以我不想使用getter和setter。我希望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 有有趣的建议。如果您必须公开许多此类变量,最好将它们全部放在一个类中。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 回答