在c ++中使用命名空间

编程入门 行业动态 更新时间:2024-10-24 12:20:25
本文介绍了在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 ++中使用命名空间

本文发布于:2023-10-23 06:04:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!