C++/CLI 中的值类

发布于 2025-01-05 07:14:04 字数 40 浏览 3 评论 0原文

在 C++/CLI 中使用值类有什么好处。值类可以包含成员函数吗?

What are the benifits of using a value class in C++/CLI.Can the value class contain member functions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦萦几度 2025-01-12 07:14:04

值类ValueType - 这意味着,每当您将其分配给相同类型的另一个变量时,整个对象都会被复制到另一个变量中,从而留下两个单独的副本。此类示例包括基本数字数据类型,例如 intbooldoubleValueTypes 是密封的,这意味着您无法从它们派生。

ref class 是引用类型 - 如果将其分配给相同类型的另一个变量,则仅复制引用。所以这两个变量基本上“指向”相同的数据。

因此,值类和引用类之间的主要区别在于复制语义。两者都可以包含方法、字段属性等。此外,您不能从值类派生。

在此上下文中使用 classstruct 关键字之间的区别在于成员的默认可见性。对于ref/value class,它是private;对于ref/value struct,它是public

一个常见的误解是 value/ref 指定存储位置(value=stack,ref=heap)。每个对象的存储位置,无论是 ValueType 还是引用类型,都是一个实现细节,任何人都不应依赖或做出假设,并且完全由运行时自行决定哪个存储位置适合任何给定上下文。

a value class is a ValueType - that means, whenever you assign it to another variable of the same type, the whole object gets copied into the other variable, leaving you with two separate copies. Examples of this are basic numeric data types like int, bool or double. ValueTypes are sealed, which means you cannot derive from them.

A ref class is a reference type - if you assign it to another variable of the same type, you copy only a reference. So the two variables basically "point" to the same data.

So the main difference between value class and ref class are the copying semantics. Both can contain Methods, fields properties and so on. Also, you cannot derive from a value class.

The difference between using the class and struct keywords in this context is the default visibility of members. It is private for ref/value class and public for ref/value struct.

A common misconception is that value/ref specify the storage location (value=stack, ref=heap). The storage location of each object, whether ValueType or reference type, is an implementation detail noone should rely on or make assumptions about and it is entirely at the runtime's discretion which storage location is appropriate in any given context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文