gpt4 book ai didi

c++ - 重载函数而不重写它们的整个定义

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:15 25 4
gpt4 key购买 nike

请看下面的例子:

class bar{
private:
unsigned _timeout;
public:
bool foo(unsigned arg);
bool foo(unsigned arg, unsigned timeout);
};

bool bar::foo(unsigned arg){
/*50 lines of code*/
if (_timeout > 4)
//...
}

bool bar::foo(unsigned arg, unsigned timeout){
/*50 lines of code*/
if (timeout > 4)
//...
}

如您所见,这些函数仅在一行中有所不同 - 第一个函数使用私有(private)成员 _timeout,第二个函数检查作为参数传递的变量超时。这里的问题是,我必须重写整个 ~50 行代码才能重载此函数。有什么解决方法吗?

最佳答案

两种选择:要么将通用功能提取到它自己的函数中(重构),要么调用另一个。

在您的情况下,您可以这样定义第一个重载:

bool bar::foo(unsigned arg) {
return foo(arg, _timeout);
}

总的来说,重构也是一个不错的方法:

void bar::foo_inner(unsigned arg) { // or however it should be declared
// 50 lines of code
}

bool bar::foo(unsigned arg) {
foo_inner(arg);
if (_timeout < 4)
...
}

bool bar::foo(unsigned arg, unsigned timeout) {
foo_inner(arg);
if (timeout < 4)
...
}

关于c++ - 重载函数而不重写它们的整个定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484022/

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