gpt4 book ai didi

c++ - 在 if 语句中调用重载的构造函数失败

转载 作者:行者123 更新时间:2023-11-28 01:44:17 26 4
gpt4 key购买 nike

所以我有一个 if 语句来决定是调用一个还是另一个构造函数。这是给我错误的代码:

detect::Wrapper detector;

if (detectorFileNameSpecified){
detector = detect::Wrapper(detectorFileName,
saveImages,
learnOrDetect,
verbosity);
}
else {
detector = detect::Wrapper(saveImages,
learnOrDetect,
verbosity);
}

detector.setFind(findAlgNo);
detector.setLD(LDAlgNo);

detector.run();

g++ 给我这些错误:

main.cpp:126:15: error: use of deleted function ‘detect::Wrapper& detect::Wrapper::operator=(detect::Wrapper&&)’
verbosity);
^
In file included from main.cpp:1:0:
wrapper.hpp:14:9: note: ‘detect::Wrapper& detect::Wrapper::operator=(detect::Wrapper&&)’ is implicitly deleted because the default definition would be ill-formed:
class Wrapper{
^~~~~~~

但是,如果我以创建冗余代码的天真方式来做,它会完美地工作。

if (detectorFileNameSpecified){
detect::Wrapper detector(detectorFileName,
saveImages,
learnOrDetect,
verbosity);

detector.setFind(findAlgNo);
detector.setLD(LDAlgNo);

detector.run();
}
else {
detect::Wrapper detector(saveImages,
learnOrDetect,
verbosity);

detector.setFind(findAlgNo);
detector.setLD(LDAlgNo);

detector.run();
}

我想做的就是减少代码中的冗余,而不必在每次需要不同的构造函数时都编写 .setFind() 等部分。我不确定如何解决这个问题。

最佳答案

通过创建函数:

void doJob(detect::Wrapper&& detector)
{
detector.setFind(findAlgNo);
detector.setLD(LDAlgNo);

detector.run();
}

然后您可以将代码分解为:

if (detectorFileNameSpecified){
doJob(detect::Wrapper(detectorFileName, saveImages, learnOrDetect, verbosity));
} else {
doJob(detect::Wrapper(saveImages, learnOrDetect, verbosity));
}

关于c++ - 在 if 语句中调用重载的构造函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45841330/

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