C :如何使一组派生的类能够访问一个类的私人成员
C++: how to make a group of derived classes be able to access private members of one class?
假设一个类: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);
}
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 使用只有一个成员的工会的目的是什么?
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- std::mutex作为一个成员变量对多个线程来说是安全的吗
- 使用线程从另一个成员函数调用一个Member函数
- 如何通过指针将模板成员函数传递给另一个成员函数
- 只有一个成员的匿名联盟
- 复制一个对象并使两者共享一个成员变量 (C++)
- 初始化指针或引用成员变量以指向另一个成员
- 在另一个成员函数中调用成员函数时'int'之前的预期主表达式
- C 将成员函数作为参数传递给另一个成员函数
- 将结构编写为二进制,其中一个成员是字符串
- 如何在另一个成员函数中修改具有常量返回类型的成员函数的返回值
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- 如何使一个成员变量等于在main()中设置的另一个成员变量
- 在另一个成员中动态添加类成员
- 在对结构数组的一个成员进行排序后,移动其成员的其余部分
- 将类成员函数作为参数从同一类的另一个成员函数传递