在if语句

时间:2017-08-23 13:36:34

标签: c++ class constructor

所以我有一个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()等部分。我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:1)

为避免代码重复,您可以采取的措施是使用指针并绕过已删除的赋值运算符:

std::unique_ptr<detect::Wrapper> detector; // <<<<<<<<<<<

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

// Note the -> to dereference    
detector->setFind(findAlgNo);
detector->setLD(LDAlgNo);

detector->run();

答案 1 :(得分:1)

通过创建功能:

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));
}