(原創) C++若參考到的class在其他檔案,須手動#include,C#則不必 (C/C++) (.NET) (C#)
Abstract
對C++ Programer來說,這是一個很白痴的標題,但對C# Programmer來說,卻是不同的感受...
Introduction
我們來看看C++和C#的寫法
C++ / Class1.cpp
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cpp / Class1.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9class Class1 {
10public:
11 int x;
12 Class1() : x(0) {};
13};
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cpp / Class1.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9class Class1 {
10public:
11 int x;
12 Class1() : x(0) {};
13};
Main.cpp
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cpp / Class1.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9#include <iostream>
10#include "Class1.cpp"
11
12using namespace std;
13
14int main() {
15 Class1 obj1;
16
17 cout << obj1.x << endl;
18}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cpp / Class1.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9#include <iostream>
10#include "Class1.cpp"
11
12using namespace std;
13
14int main() {
15 Class1 obj1;
16
17 cout << obj1.x << endl;
18}
C#
Class1.cs
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cs / Class1.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9class Class1 {
10 public int x;
11}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cs / Class1.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9class Class1 {
10 public int x;
11}
Main.cs
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cs / Class1.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9using System;
10
11class MainClass {
12 public static void Main() {
13 Class1 obj1 = new Class1();
14
15 Console.WriteLine(obj1.x);
16 }
17}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : Main.cs / Class1.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo the difference between C++ and C#
7Release : 01/13/2007 1.0
8*/
9using System;
10
11class MainClass {
12 public static void Main() {
13 Class1 obj1 = new Class1();
14
15 Console.WriteLine(obj1.x);
16 }
17}
執行結果
0
請按任意鍵繼續 . . .
請按任意鍵繼續 . . .
在C++中,若class在其他檔案,要用到該class的程式必須手動加上#include "filename.cpp",但C#卻不必,只要在同一個project中,C#自動就抓的到,或許C# compiler背後自動幫你加上#include,但不管如何,C#省掉了這個步驟。
除此之外,我們還看到由於C++繼承了C語言,built-in type如int並沒有預設值,所以得在constructor加上initializer list對int加上初始值,但C#卻不必,這算是C++的一大包袱。
Conclusion
C#的確是大幅簡化了C++在語法上的複雜度。