programing

헤더 및 소스 (CPP)에 C ++ 네임 스페이스 만들기

nasanasas 2020. 10. 8. 08:06
반응형

헤더 및 소스 (CPP)에 C ++ 네임 스페이스 만들기


헤더와 cpp 파일 내용을 네임 스페이스에 모두 래핑하거나 헤더 콘텐츠 만 래핑 한 다음 cpp 파일에서 네임 스페이스사용 하는 것 사이에 차이가 있습니까?

차이점은 문제를 일으킬 수있는 정렬 성능 저하 또는 약간 다른 의미 체계를 의미합니다.

예:

// header
namespace X
{
  class Foo
  {
  public:
    void TheFunc();
  };
}

// cpp
namespace X
{
  void Foo::TheFunc()
  {
    return;
  }
}

VS

// header
namespace X
{
  class Foo
  {
  public:
    void TheFunc();
  };
}

// cpp
using namespace X;
{
  void Foo::TheFunc()
  {
    return;
  }
} 

차이가없는 경우 선호하는 형식은 무엇이며 그 이유는 무엇입니까?


네임 스페이스는 충돌하지 않도록 함수 서명을 조작하는 방법 일뿐입니다. 일부는 첫 번째 방법을 선호하고 다른 일부는 두 번째 버전을 선호합니다. 두 버전 모두 컴파일 시간 성능에 영향을주지 않습니다. 네임 스페이스는 컴파일 시간 엔터티 일뿐입니다.

네임 스페이스를 사용할 때 발생하는 유일한 문제는 동일한 중첩 네임 스페이스 이름 (예 :)이있을 때 X::X::Foo입니다. 그렇게하면 키워드를 사용하거나 사용하지 않고 더 많은 혼란을 야기합니다.


"네임 스페이스 X"와 "네임 스페이스 X 사용"의 차이점은 첫 번째 선언에서는 새로운 선언이 네임 스페이스 아래에 있고 두 번째 선언에서는 그렇지 않습니다.

귀하의 예에는 새로운 선언이 없으므로 차이가 없으므로 선호하는 방법이 없습니다.


결과가 동일 할 수 있기 때문에 성능상의 불이익은 없지만 Foo네임 스페이스에을 넣으면 Foo다른 네임 스페이스에 s 가있는 경우 암시 적으로 모호함이 발생합니다 . 실제로 코드 푸바를 얻을 수 있습니다. using이 목적으로 사용하지 않는 것이 좋습니다 .

그리고 당신은 ;-) {후에 using namespace잃었습니다.


If the second one compiles as well, there should be no differences. Namespaces are processed in compile-time and should not affect the runtime actions.

But for design issues, second is horrible. Even if it compiles (not sure), it makes no sense at all.


The Foo::TheFunc() is not in the correct namespacein the VS-case. Use 'void X::Foo::TheFunc() {}' to implement the function in the correct namespace (X).


In case if you do wrap only the .h content you have to write using namespace ... in cpp file otherwise you every time working on the valid namespace. Normally you wrap both .cpp and .h files otherwise you are in risk to use objects from another namespace which may generate a lot of problems.


I think right thing to do here is to use namespace for scoping.

namespace catagory
{
    enum status
    {
      none,
      active,
      paused
    }
};

void func()
{
    catagory::status status;
    status = category::active;
}

참고URL : https://stackoverflow.com/questions/8210935/creating-a-c-namespace-in-header-and-source-cpp

반응형