[英]What is the correct way to encapsulate helper functions in C++?
给定一个类:
class myClass{
// ...
private:
int helperFuncForA();
int secondhelperFuncForA();
public:
void A();
// ...
};
假设辅助函数不在A
之外A
; 我如何封装它们,以便在A
之外调用它们是不可能的? 我要不要:
class myClass{
// ...
public:
class {
private:
int helperFuncForA();
int secondhelperFuncForA();
public:
void call();
} A;
// ...
};
然后通过写入调用:
myClass obj;
obj.A.call();
? 也许,为了方便起见,我可以重载A
的()
运算符而不是call()
函数。 什么是正确的方法?
正确的方法是使用 lambdas:
class myClass{
// ...
private:
// remove from here
//int helperFuncForA();
//int secondhelperFuncForA();
public:
void A();
// ...
};
// somewhere
void myClass::A()
{
auto helperFuncForA = [this]() -> int
{
//...
return 1;
};
auto secondhelperFuncForA = [this]() -> int
{
//...
return 2;
};
//...
int x = helperFuncForA();
x += secondhelperFuncForA();
}
如果某些方法只能在函数 void A() 中使用,则您可能需要一个类。
但是如果你愿意,你可以做这样的事情:
#include <iostream>
class ClassTest
{
public:
struct A{
private:
void helperFunc() {
std::cout << "Executing Helper Func " << std::endl;
}
public:
void operator() (){
helperFunc();
}
};
A a;
void classFunc(){
//a.helperFunc(); <- Impossible helperFunc private
a();
}
};
int main()
{
ClassTest c;
c.classFunc();// Print : Executing Helper Func
//OR
c.a();// Print e: Executing Helper Func
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.