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

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

问题描述

我在看名字空间,我真的看不到这些和类之间的区别。
我教自己c ++我已经在线上了几本书,所以我知道我不是最有效地学习
。有人可以告诉我两者之间的区别,什么是最好的时间使用一个类在一个类。另外,我在我正在阅读的书中没有看到很多关于structs的内容。

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. Anyways 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"};

}


$ b b $ b

thanks in advance for your assistance.

推荐答案

类和结构体定义类型。您可以创建类型的对象。命名空间简单地声明一个范围,其他类型,函数,对象或命名空间可以存在于其中。你不能创建类型 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).

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

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"

/ strong>

Edit

可能值得指出的是,一切都是一个对象的语言,如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天全站免登陆