Managed Extensions for C++ 中的 Hello World
下列程式碼將說明 Hello World 在 Managed Extensions for C++ 中的樣子。
清單 1:Managed Extensions for C++ 中的 Hello World (HelloVC.cpp)
#using <mscorlib.dll>
// Allow easy reference to the System namespace classes.
using namespace System;
// The global function, main, is the application's entry point.
void main() {
// Write text to the console.
Console::WriteLine(S"Hello World using Managed Extensions for C++!");
}
雖然這整個程式只有幾行程式碼,但是有幾點需要注意,先從下列這行開始說明:
#using <mscorlib.dll>
在 Managed Extensions for C++ 中,#using
指示詞和 #import
指示詞類似,是用來合併型別程式庫 (Type Library) 中的資訊。請注意,這兩個指示詞和 #include
指示詞不同,後者是用來合併原始程式碼,而非預先建置的程式庫。此外,若要將命名空間匯入程式中 (也就是讓它方便參考 System 物件,而不使用完整的路徑名稱),還需要下列這行陳述式:
using namespace System;
接著,請看下一行:
void main() {
雖然進入點 main 沒有使用命令列引數,但是這可明顯增強非瑣碎程式。進入點也不會傳回任何值,不過,它可能會修改函式,傳回一個 32 位元的數值當成結束代碼 (Exit Code)。
再下一行是:
Console::WriteLine(S"Hello World using Managed Extensions for C++!");
程式的核心,這一行會使用 Runtime Console 型別寫入一個字串。Read、ReadLine、Write 和 WriteLine 方法都可使用 Console 型別來輸入和輸出任何字串或數值。前面曾提過,在 Managed Extensions for C++ 中,Console::WriteLine 中必須用雙冒號來表示範圍。雙冒號會將命名空間與類別名稱分開,也會將類別名稱與靜態方法分開。最後,字串前面的 S 會指示編譯器將它變成 System::String*
,這會使 Managed 程式碼中的效能比 C++ 字串常值 (String Literal) 好。
Build.bat 檔案中只要包含下列這一行,就可以建置這個程式:
cl.exe /Zi /clr HelloVC.cpp
要注意的第一個項目是 /clr 參數,它會指示編譯器依照 Runtime 的需要建立 Managed 程式碼。執行 Build.bat 會產生下列輸出:
C:\...\HelloWorld\vc>build
C:\...\HelloWorld\vc> cl.exe /Zi /clr HelloVC.cpp
Microsoft (R) C/C++ Optimizing Compiler...
Copyright (C) Microsoft Corporation 1984-2001. All rights reserved.
HelloVC.cpp
Microsoft (R) Incremental Linker ...
Copyright (C) 1992-2001 Microsoft Corporation. All rights reserved.
/out:HelloVC.exe
/debug
HelloVC.obj
最後,執行產生的可執行檔會得到下列輸出:
C:\...\HelloWorld\vc>hellovc
Hello World using Managed Extensions for C++!
請參閱
Visual C# 中的 Hello World | Visual Basic 中的 Hello World | 撰寫簡單的 .NET 元件 | 簡單元件的用戶端 | 開發教學課程摘要 | 附錄 A:瀏覽命名空間的工具