类和命名空间的区别? [英] Difference between classes and namespaces?

查看:31
本文介绍了类和命名空间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看名称空间,但我并没有真正看到这些名称和类之间的区别.我正在自学 C++ 我已经在网上找到了几本书,所以我知道我的学习效率不是最高的.无论如何,有人可以告诉我两者之间的区别,以及在课堂上使用命名空间的最佳时间是什么时候?另外,我在正在阅读的书中没有看到太多关于结构的内容.

I'm looking at namespaces and I don't really see a difference between these and classes. I'm teaching myself C++ I've gotten several books online, so I know I'm not learning the most effectively. Anyway, can someone tell me the difference between the two, and what would be the best time to use a namepace over a class? Also, I don't see much about structs in the book I'm reading.

这是格式吗?

struct go
{

  goNow(){ cout << "go Now"};

}

提前感谢您的帮助.

推荐答案

类和结构定义类型.您可以创建一个类型的对象.命名空间只是声明一个范围,在该范围内可以存在其他类型、函数、对象或命名空间.您不能创建 std 类型的对象(当然,除非您创建了一个名为 std 的类型,它会隐藏 std 命名空间).

Classes and structs define types. You can create an object of a type. Namespaces simply declare a scope inside which other types, functions, objects, or namespaces can exist. You can't create an object of type std (unless of course you created a type called std, which would hide the std namespace).

当您在结构/类(方法)中定义函数时,您是在说此函数是对关联数据的基本操作".当你在命名空间中定义一个函数时,你是在说这个函数在逻辑上与命名空间中的其他函数、类型和对象相关"

When you define a function inside a struct/class (a method) you're saying "This function is a fundamental operation on the associated data". When you define a function inside a namespace you're saying "This function is logically related to other functions, types, and objects in the namespace"

编辑

可能值得指出的是,像 Java 和 C# 这样的一切都是对象"语言经常使用类,就好像它们是命名空间一样,因为它们不允许自由"函数.这可能就是混乱的来源.如果你有一个其他语言的类只包含静态成员,你会希望在 C++ 版本中使用命名空间和自由函数.

It's probably worth pointing out that "everything is an object" languages like Java and C# regularly use classes as if they were namespaces because they don't allow "free" functions. This may be where the confusion comes from. If you have a class in another language that contains nothing but static members, you would want to use a namespace and free functions in the C++ version.

这篇关于类和命名空间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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