gpt4 book ai didi

c++ - 在 C++ 中封装辅助函数的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-03 06:54:32 25 4
gpt4 key购买 nike

给定一个类:

class myClass{
// ...

private:
int helperFuncForA();
int secondhelperFuncForA();
public:
void 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();
}

关于c++ - 在 C++ 中封装辅助函数的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63841865/

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