简体   繁体   English

C++ 中的命名空间重构

[英]Namespace refactoring in C++

I am refactoring namespaces of small part of a large project.我正在重构一个大型项目的一小部分的命名空间。 So I have refactored following 2 files which had Oldname as the namespace to x::y::z .因此,我将以下 2 个以Oldname作为命名空间的文件重构为x::y::z

file1.hpp文件1.hpp

namespace x::y::z
{

Class abc
{
public:
       void funcA(type1 arg1, type2 arg2)   
}

file1.cpp文件1.cpp

#include "file1.hpp"

namespace x::y::z
{
void abc::funcA(type1 arg1, type2 arg2)
{
--------
}
}

Now I am resolving this file 2 which has dependencies with the above file.现在我正在解析这个文件 2,它与上述文件有依赖关系。 I do not want to change the namespace of this file, but just modify the functions that depend on the above files.我不想改变这个文件的命名空间,只是修改依赖于上述文件的函数。

file2.cpp文件2.cpp

#include "file1.hpp"

namespace Oldname
{
 void abc::funcA(type1 arg1, type2 arg2)
{
      mock("txt")
         .actualCall("abc.funcA")
         .withParameter("arg1", arg1)
         .withParameter("arg2", arg2)

}
}

I tried to make it as follows,我试图使它如下,

namespace Oldname
{
   void x::y::z::abc::funcA(type1 arg1, type2 arg2)
{
      mock("txt")
          .actualcall("abc.funcA")
          .withParameter("arg1",arg1)
          .withParameter("arg2",arg2)
}
}

However, I get the following error,但是,我收到以下错误,

error: cannot define or redeclare 'funcA' here because namespace 'Oldname' does not enclose namespace 'abc'

Can someone help how to resolve this error?有人可以帮助如何解决此错误吗?

Fromcppreference.com (emphasis added):来自cppreference.com (强调添加):

Out-of-namespace definitions and redeclarations are only allowed after the point of declaration, only at namespace scope, and only in namespaces that enclose the original namespace (including the global namespace) and they must use qualified-id syntax名称空间外定义和重新声明仅允许在声明点之后,仅在名称空间 scope 中,并且仅在包含原始名称空间(包括全局名称空间)的名称空间中,并且它们必须使用限定 ID 语法

Given this rule, the definition of ::x::y::z::abc::funcA is allowed鉴于此规则,允许::x::y::z::abc::funcA的定义

  • in the definition of the class ( ::x::y::z::abc ),在 class ( ::x::y::z::abc ) 的定义中,
  • in namespace ::x::y::z ,在命名空间::x::y::z中,
  • in namespace ::x::y ,在命名空间::x::y中,
  • in namespace ::x , or在命名空间::x中,或
  • in the global namespace.在全局命名空间中。

It is not allowed in any other namespaces.在任何其他命名空间中都不允许这样做。 In particular, it is not allowed in the namespace Oldname .特别是在命名空间Oldname中是不允许的。 To resolve this error (without introducing namespace x to file2.cpp ), take your definition out of Oldname and put it in the global namespace.要解决此错误(不将namespace x引入file2.cpp ),请将您的定义从Oldname中取出并将其放入全局命名空间中。 Or maybe re-think how your namespaces are set up.或者重新考虑您的命名空间是如何设置的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM