2017-03-30 100 views
0

类路径的构造函数最初包含以下代码,用于检查文件中是否存在元素(“gpx”,“rte”等)。它应该运行。C++中的重构代码

if (! elementExists(source,"gpx")) 
    { 
     oss << endl << "no gpx tag"; 
     constructorReport = oss.str(); 
     constructorSucceeded = false; 
     return; 
    } 
    if (! elementExists(source,"rte")) 
    { 
     oss << endl << "no rte tag"; 
     constructorReport = oss.str(); 
     constructorSucceeded = false; 
     return; 
    } 

我试着引入一个函数来替换这些if语句。该程序的构建没问题。

void Route::constCheck(string source, string type) 
{ 

    if (! XML_Parser::elementExists(source, type)) 
    { 
     std::ostringstream oss; 
     oss << std::endl << "no" << type <<" tag"; 
     constructorReport = oss.str(); 
     constructorSucceeded = false; 
     return; 
    } 
} 

我已经改变了它检查产生错误的GPX文件,但与我的附加功能,它继续好像没有错误。

任何帮助表示赞赏,请让我知道,如果你需要更多的信息。我试图按照指导原则保持代码轻松。

+2

你觉得呢'return'呢? –

+0

返回void函数没有必要:)但这里的问题在于其他地方。 – 0xDEFACED

+0

你能告诉我们你如何以及在哪里执行你的新功能吗? – 0xDEFACED

回答

0

在您的原始代码中,您在第一次测试失败时从函数返回,您不会继续尝试其他测试。

现在您已经将测试移到了函数中,调用者无法知道测试是否失败,因此它将执行所有测试,并且在其中一个失败时不会从其函数返回。你需要这个函数来返回一个指示它是否失败的布尔值。

bool Route::constCheck(string source, string type) 
{ 

    if (! XML_Parser::elementExists(source, type)) 
    { 
     std::ostringstream oss; 
     oss << std::endl << "no" << type <<" tag"; 
     constructorReport = oss.str(); 
     constructorSucceeded = false; 
     return false; 
    } 
    return true; 
} 

然后更换为原来的代码是这样:

if (!constCheck(source, "gpx")) { 
    return; 
} 
if (!constCheck(source, "rte")) { 
    return; 
} 
+0

我明白我出错的地方。代码完美工作,我只是不得不忽略!当调用它时。谢谢您的帮助!。 – JohnDoe