警告:'name'的声明会影响前一个本地

时间:2018-01-31 12:49:31

标签: c++

我在这里有一个非常简单的片段:

std::string testName;

if (argc < 2) {
    std::string testName = "default";
}
else {
    std::string testName = argv[2];
}

由于某种原因,编译器给了我2个警告;

warning: declaration of ‘testName’ shadows a previous local [-Wshadow]
   std::string testName = "default";
               ^

note: shadowed declaration is here
  std::string testName;
              ^

warning: declaration of ‘testName’ shadows a previous local [-Wshadow]
   std::string testName = argv[2];
               ^

note: shadowed declaration is here
  std::string testName;
              ^

我感觉生气和愚蠢,感谢帮助!

1 个答案:

答案 0 :(得分:8)

您获得的警告是由于您在条件中声明了一个新变量。要解决此问题,请删除条件中的std::string

std::string testName;

if (argc < 2) {
    testName = "default"; // Prefixing with std::string creates a new variable
}
else {
    testName = argv[2]; // Not doing so assigns the old variable
}

如果你想在一行上完成所有操作,你可以使用三元运算符执行以下操作,因为初始化可能比以后声明和分配更好。

std::string testName = argc < 2 ? "default" : argv[2];