简体   繁体   English

当传递的lambda使用私有成员变量时,它们是否违反封装?

[英]Does passing lambdas violate encapsulation when they use a private member variable?

I wrote a function to pass to a third party's class. 我编写了一个传递给第三方课程的函数。 A static function worked fine until the function needed access to a private member variable to do its work. 静态函数可以正常工作,直到该函数需要访问私有成员变量以完成其工作为止。 I can do that using a lambda expression (given that it is converted to std::function either automatically or by casting). 我可以使用lambda表达式来做到这一点(假设它可以自动或通过强制转换为std :: function)。

Example: 例:

void classA::doingThings()
{
...
    classB::needsHelpToDoAThing(
    [&](std::type foo) -> size_t { return myFunction(foo); }
    );
...
}

size_t class::myFunction(type foo){
...
type someVar = m_somePrivateMember ...(some work)
...
}

But I don't really understand what I'm doing. 但是我真的不明白我在做什么。 Now this other class is using private member variables from a different class. 现在,该其他类正在使用来自其他类的私有成员变量。 Doesn't this violate encapsulation? 这不是违反封装吗? Is this a hack or am I missing/misunderstanding a concept? 这是hack吗,还是我缺少/误解了一个概念?

Encapsulation is the idea that other code doesn't get to poke around in your innards willy-nilly. 封装是这样的想法,即其他代码不会在您的内心里随意地乱搞。

Here you created a helper function that can poke around in your innards. 在这里,您创建了一个可以在内部查看的辅助函数。 This helper function is part of your innards, even if you pass it to someone else. 即使您将其传递给其他人,该辅助功能也是您内在的一部分

This no more breaks encapsulation than a member method accessing private data. 这不比访问私有数据的成员方法破坏封装。 While it isn't part of the interface of the class explicitly, it is still part of the implementation. 虽然它不是明确地属于类的接口的一部分,但仍是实现的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当变量恰好是指针时,如何在非成员函数中使用私有成员变量? - How can I use a private member variable in a non-member function, when the variable happens to be a pointer? 声明私有时的静态成员变量 - static member variable when declared private 将成员函数和lambdas都传递给std :: function - Passing both member functions and lambdas to std::function 导出和销毁封装,还是违反 DRY? - Derive & Destroy Encapsulation, or Violate DRY? 这两个类是否违反了封装? - Do these two classes violate encapsulation? 如果我在类成员函数的定义中使用全局变量,是否违反了封装? - Is encapsulation violated, if I use a global variable in a class member function's definition? 从构造函数传递到成员函数时,私有成员变量为null - Private member variable is null when passed from constructor to member function C ++:使用指针作为私有成员变量而不破坏封装吗? - C++: Using pointers as private member variables without breaking encapsulation? 模板 class 派生自私有成员 class 破坏封装 - Template class derived from private member class breaks encapsulation 如何利用对私有(结构)成员的公共常量引用进行代码封装 - How to utilize a public constant reference to a private (struct) member for code encapsulation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM