博客园  :: 首页  :: 联系 :: 管理

value struct and value class

Posted on 2006-12-14 01:24  sunrack  阅读(800)  评论(0编辑  收藏  举报
The value struct and value class data types are basically C++/CLI’s equivalent to traditional C++’s
class and struct data types but with an added bonus. Both are unmanaged (not garbage collected)
constructs used to combine multiple data types and methods (or functions) into a single data type.
Then when a new instance of the data type is created, it is allocated either to the stack or CRT heap.
The added bonus is that a copy of value struct or value class can be assigned to a variable
on the managed heap. Notice I said “a copy,” because the original value struct and value class
remains unmanaged. For those of you new to the C++ world, I cover the class and struct in detail in
Chapter 21.

Unsafe Code A struct and class without the prefix value or ref are unsafe code, as they are referenced
using pointers and not handles. Thus, a struct and a class are placed on the CRT heap, which you have to
maintain yourself.


The only difference between a value struct and a value class is the default access of their
members; value struct members are public, whereas value class members are private. I cover
public and private access in Chapter 3.
The value struct and value class are C++/CLI’s way of providing programmers with a method
of creating their own value types, thus allowing for expansion beyond the basic fundamental types.
All value structs and value classes are derived from the .NET Framework class library’s
System::ValueType, which allows for the value struct’s and value class’s ability to be placed on the stack. A value struct and value class can inherit from only interfaces. Trying to inherit from a
value struct or value class results in a compile time error.
Listing 2-8 is a simple example of a value class called Coord3D. It is made up of three doubles,
a constructor, and a Write() method. I cover constructors and overriding in Chapter 3. The main()
function creates the two copies of Coord3D on the stack, with one using the default constructor, and
the other using the one user-defined constructor. Notice that to assign a value class to another, you
simply use the equal sign (=).

Listing 2-8. A value class in Action
using namespace System;
// Value class in Action
value class Coord3D
{
public:
double x;
double y;
double z;
Coord3D (
double x, double y, double z)
{
this->= x;
this->= y;
this->= z;
}

String
^ Write()
{
return String::Format("{0},{1},{2}", x, y, z);
}

}
;
void main()
{
Coord3D coordA;
Coord3D coordB(
1,2,3);
coordA 
= coordB; // Assign is simply an =
coordA.x += 5.5// Operations work just as usual
coordA.y *= 2.7;
coordA.z 
/= 1.3;
Console::WriteLine(coordB.Write());
Console::WriteLine(coordA.x);
Console::WriteLine(coordA.y);
Console::WriteLine(coordA.z);
}