首页 > 解决方案 > 如何处理参数名称阴影方法?

问题描述

下面的代码使用 gcc 4.9 和 -std=c++14 -Wshadow 编译产生以下警告:

main.cpp:12:24: warning: declaration of ‘id’ shadows a member of 'this' [-Wshadow]

主.cpp:

#include <string>

class Foo
{
public:
   Foo(std::string id);
   const std::string& id() const noexcept;
private:
   const std::string m_id;
};

Foo::Foo(std::string id) : m_id(id) {}
const std::string& Foo::id() const noexcept { return m_id; }

int main(int argc, char** argv) { return 0; }

我继承的代码库包含很多这样的代码。原始作者选择的命名约定(我必须坚持)要求 getter 不以“get”为前缀。仅仅为了摆脱这个警告而重命名诸如id之类的参数听起来像很多工作都是徒劳的。目前我倾向于添加一个尾随下划线 - 它只需要在 .cpp 文件中完成,这样丑陋就不会到达公共标题。有人有其他想法吗?

标签: c++gcc

解决方案


推荐阅读