C ++ / CLI中的值类 [英] Value Class in C++/CLI
问题描述
在C ++ / CLI中使用值类的好处是什么?值类包含成员函数?
值类
是 ValueType
- 这意味着,无论何时将它分配给同一类型的另一个变量,整个对象都将复制到另一个变量中,从而保留两个单独的副本。这样的例子是 int
, bool
或 double
。 ValueTypes
是密封的,这意味着你不能从它们派生。
ref class
是引用类型 - 如果将其分配给同一类型的另一个变量,只有参考。所以这两个变量基本上指向相同的数据。
因此值类
和 ref类之间的主要区别
是复制语义。两者都可以包含方法,字段属性等。此外,您不能从值类派生
。
使用类在此上下文中的
和 struct
关键字是成员的默认可见性。它是 private
for ref / value class
和 public
一个常见的误解是,value / ref指定了存储位置(value = stack, ref / value struct
。
< ref = heap)。每个对象的存储位置,不管是ValueType还是引用类型,都是一个实现细节,没有人应该依赖或做出假设,它完全由运行时自行决定哪个存储位置在任何给定的上下文中是适当的。
What are the benifits of using a value class in C++/CLI.Can the value class contain member functions?
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.
这篇关于C ++ / CLI中的值类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!