C++ 名称与 typedef 别名和继承名称的冲突

标签 c++ inheritance namespaces typedef

我遇到名称冲突问题。我正在编辑大量类型定义的包装系统,我想避免以下名称冲突:

namespace NS{
  struct Interface{};
}
struct OldInterface: private NS::Interface{};
typedef OldInterface Interface;
struct Another : Interface{ // Derived correctly from OldInterface
  Another(Interface p){} // C2247 - in struct scope Interface means NS::Interface
};

我试过命名空间——但在对象中它被隐式地切割了。 我也试过私有(private)继承,这导致我又犯了一个错误。

所以问题:如何将它与上述名称一起使用? 例如,如何强制结构内作用域使用命名空间继承名称?

最佳答案

您可以明确声明您想要全局命名空间中的Interface:

struct Another : Interface{
  Another(::Interface p){}
  //      ^^
};

如果你发现自己经常需要限定这个,你可以为该类型引入一个本地别名:

struct Another : Interface{
  using Interface = ::Interface;
  //or typedef ::Interface Interface if you can't use C++11
  Another(Interface p){}
};

关于C++ 名称与 typedef 别名和继承名称的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33937600/

相关文章:

c# - 关于 C# 命名空间结构的困惑

c++ - CMake 为 VS 项目生成循环依赖项,但不生成 make 文件。如何避免?

c++ - 如何打印出Mat图像中的像素值

c++ - 在基类构造函数中使用 `this` 是否有效?

c# - VB.NET命名空间缩写: How do I make this work in equivalent C# code?

.net - 命名空间未通过 DataContractSerializer 从 XML 根中删除

c++ - 在 CentOS 上使用 OpenGL 支持从源代码编译 Qt 4.8.3

c++ - 基类和派生类分配

python - 为什么在 python 中使用 dual __init__?

Django - 类的子类的所有实例的唯一ID?