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

來源:互聯網
上載者:User

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

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 */

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,其實只要觀念清楚,習慣了就好。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.