gpt4 book ai didi

c++ - 从类外调用 lambda 中的私有(private)函数

转载 作者:太空宇宙 更新时间:2023-11-03 10:23:37 25 4
gpt4 key购买 nike

在我当前的项目中,我试图将私有(private)成员函数作为参数传递给另一个函数。在我的代码中,另一个函数是另一个类的成员函数,但为了简单起见,这里它是一个自由函数。

void outside_function(std::function<void(int)> func) {
// do something with func
}


class MyClass {
public:
void run();

private:
bool my_func(double); // defined in source file
};

现在,在 run 中,我想将 my_func 作为参数放入 outside_function 中。由于 run 的签名不符合参数的要求,我不能简单地传递它。使用 adapter pattern这是我的第一次尝试,那时我被提醒成员函数隐式地将 this 指针作为第一个参数。 This答案建议使用 lambda 表达式,这就是我所做的。

void MyClass::run() {
outside_function([this](int a) -> void {
double d = static_cast<double>(a);
this->my_func(d);
});
}

为什么会这样?根据我的理解,outside_function 无法访问 my_func。为什么我不必先公开 my_func ?是编译器执行的操作还是我不知道的某些 C++ 规则?

此外,这种方法是否有任何可能破坏我的代码的问题?

最佳答案

private 访问说明符仅限制对象name 在类外可见(无法查找)。对象本身与任何其他成员一样。

[class.access]/1

A member of a class can be

(1.1) private; that is, its name can be used only by members and friends of the class in which it is declared.

(1.2) protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see [class.protected]).

(1.3) public; that is, its name can be used anywhere without access restriction.

关于c++ - 从类外调用 lambda 中的私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50176896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com