C :如何使一组派生的类能够访问一个类的私人成员

C++: how to make a group of derived classes be able to access private members of one class?

本文关键字:一个 成员 何使一 派生 访问      更新时间:2023-10-16

假设一个类:library

我们有一组来自基类库的派生类,例如:孩子,父母,学生,等

在库中,有一组(吨)私人成员变量。由于图书馆中有很多私人会员,因此我不想使用乏味的Getter和Setter。再加上LibraryCustomer派生的类通常是指这些成员。getter和setter不方便。

为了使这些Librarycustomers访问库中的那些私人成员,我需要声称这些图书馆库作为图书馆中的朋友类。

但是,由于派生的课程不断增长,我不想在班级库中添加它们。

在库中添加基类Librarycustomer作为朋友似乎不起作用。那么什么是更好的方法?

[更新]我想访问库中的大量私人成员变量。由于有很多,所以我不想使用getter和setter。我希望来自LibraryCustomer的派生类可以在库中自由访问这些私人成员变量。

提供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/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);
}