如何使容器的元素只能调用容器一个私有函数的结构
How to make structure where container's element can call containers only one private function
我想制作一个结构,其中容器元素可以向集装箱发出回调,但我不想让它成为public
。我该怎么做?我不能保证,也许我需要静态地给容器的私有函数对元素的地址,或者以某种方式使用friend
?顺便说一句,元素应该"查看"其他容器的私有函数。
例如,class Cont
存储class Elem
。Cont
具有私有函数void callback();
。Elem
知道他在哪个Cont
中,并且可以调用回调函数。Cont
之外的任何人都不能使用回调函数。
在Elem
构造函数中,您可以为回调设置一个参数(例如使用std::function
或类似方法(,并将其存储在Elem
类中。然后,当需要调用回调时,只需调用它即可。
您也可以在Elem
中创建一个"setter"函数来设置回调。
完整示例
#include <iostream>
#include <string>
#include <functional>
#include <vector>
class Elem
{
private:
int value_;
std::function<void(const std::string&)> callback_;
public:
Elem(int v, std::function<void(const std::string&)> cb)
: value_{v}, callback_{cb}
{}
void some_function() const
{
callback_("Elem with value " + std::to_string(value_));
}
};
class Cont
{
private:
std::vector<Elem> elements_;
void private_function(const std::string& s)
{
std::cout << "In private function: " << s << 'n';
}
public:
void add_value(const int v)
{
elements_.push_back(Elem(v, std::bind(&Cont::private_function, this, std::placeholders::_1)));
}
std::vector<Elem>::const_iterator begin() const
{
return std::begin(elements_);
}
std::vector<Elem>::const_iterator end() const
{
return std::end(elements_);
}
};
int main()
{
Cont c;
// Add some elements
for (int i = 1; i <= 10; ++i)
c.add_value(i);
// Call callback function
for (const auto& e : c)
e.some_function();
}
输出:
在私有函数中:值为1的Elem在私有函数中:值为2的Elem在私有函数中:值为3的Elem在私有函数中:值为4的Elem在私人功能中:值为5的Elem在私人功能中:Elem值为6在私人功能中:Elem值为7在私人功能中:Elem值为8在私人功能中:Elem值为9在私人功能中:Elem值为10
看看它在行动中。
在上面的代码中,私有函数Cont::private_function
对于Elem
类来说是完全未知的,不能直接调用。但是,我们可以使用参数将它传递给Elem
类,然后从Elem
类内部调用它,而不公开私有函数。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针