(原創) 如何使用struct? (C/C++) (.NET) (C++/CLI)

Abstruct
C++/CLI分ref struct與value struct,這裡介紹常用的value struct寫法。

Introduction
使用環境:Visual C++ 9.0 / Visual Studio 2008

struct_value.cpp / C++/CLI 2

1 /* 
2 (C) OOMusou 2007 http://oomusou.cnblogs.com
3 
4 Filename    : struct_value.cpp
5 Compiler    : Visual C++ 9.0 / C++/CLI 2.0
6 Description : Demo how to use struct in C++/CLI 2.0
7 Release     : 07/23/2008 1.0
8 */
9 
10 #include "stdafx.h"
11 
12 using namespace System;
13 
14 public value struct Student {
15   Int32    id;  // System::Int32 id;
16   String^ name; // System::String^ name;
17 };
18 
19 void func(value struct Student %child) {
20   Console::WriteLine("id={0}", child.id);
21   Console::WriteLine("Name={0}", child.name);
22 }
23 
24 int main(array<String ^> ^args) {
25   value struct Student son;
26   son.id = 1;
27   son.name = "Clare";
28   func(son);
29 }
30 


執行結果

id=1
Name
=Clare


14行

public value struct Student {


預設為private,不能跨assembly,public才能跨assembly。struct分兩種,value struct在stack,ref struct在heap,一般來說,struct都很小,適合建在stack,速度較快。

16行

String^ name; // System::String^ name;


若要使用.NET的string,別忘了S要大寫,之所以能這樣寫,是因為12行已經using namespace System了,由於.net的String是ref type,所以要使用handle ^。

值得一提的是,由於C++/CLI也可以使用STL的string,所以只要#include <string> 且 using namespace std;,string name的寫法也是合法,這時name為STL的std::string。

25行

value struct Student son;


宣告struct變數時,要連value也寫上去,這與標準C++不同。

21行

void func(value struct Student %child) {


由於struct是value type,所以如何pass by reference就很重要,標準C++使用&為reference,C++/CLI使用%為reference。

Conclusion
C++/CLI的語法較為繁瑣,主要是因為C++/CLI同時要支援標準C++與.NET兩套標準,很多keyword都已經被標準C++用走了,只好額外增加keyword,其實只要觀念清楚,習慣了就好。

posted on 2008-07-23 20:45  真 OO无双  阅读(6221)  评论(2编辑  收藏  举报

导航