在c ++中使用命名空间 [英] Usage of namespaces in c++

查看:132
本文介绍了在c ++中使用命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用下面的代码片段中的命名空间吗?代码在gcc和msvc中编译,让我对命名空间使用感到困惑。



在f1.h:

 
命名空间我的
{
void foo();
}

在f1.cpp
`



 
void My :: foo()
{
}




我认为函数应该定义为:

 
命名空间我的{
void foo(){}
}

p>

感谢

解决方案

将命名空间成员定义为只要其名称以其命名空间的名称为前缀,并且该定义实际上发生在包含它的命名空间中。它不能发生在嵌套在成员命名空间内的命名空间中。

 命名空间A {void f(); } 
void A :: f(){} //前缀A ::

命名空间B {}
void B :: f无效!不在B中声明!

命名空间C {void f(); }
namespace D {void C :: f(){}} //无效! D不包含C

命名空间E {
void f();
命名空间F {
void E :: f(){} //无效! F嵌套在E里面!
}
}

这是和类成员相同的东西,也可以定义其类之外的函数,只要在名称前面加上类的名称即可。然而,对于类,命名空间成员必须首先在它们各自的命名空间中声明,然后才能被外层定义。


Can we use namespaces like in below snippet? The code compiles in both gcc and msvc, leaving me confused about namespace usage.

In f1.h:

namespace My
{
 void foo();
}

In f1.cpp `

void My::foo()
{
}

I thought that the function should be defined as:

namespace My {
void foo() {}
}

Can anyone kindly explain?

Thanks

解决方案

It's legal to define namespace members outside of their namespace as long as their name is prefixed with the name of their namespace, and the definition actually occurs in a namespace that encloses it. It can't happen in a namespace that's nested inside the member namespace.

namespace A { void f(); }
void A::f() { } // prefix with "A::"

namespace B { }
void B::f() { } // invalid! not declared in B!

namespace C { void f(); }
namespace D { void C::f() { } } // invalid! D doesn't enclose C

namespace E {
  void f();
  namespace F {
    void E::f() { } // invalid! F is nested inside E!
  }
}

It's the same stuff as for class members, where you can also define functions outside of their class, as long as you prefix the names with the name of the class. However as for classes, namespace members must be first declared in their respective namespace before they can be defined outside out it.

这篇关于在c ++中使用命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆