C struct和class的比較

2021-07-24 01:10:22 字數 2399 閱讀 1932

什麼是class?

class是我們通常所說的類,是物件導向程式設計的基本概念,一種可以自定義的資料結構型別,

c#中的class

通常包含字段、屬性、方法、建構函式、索引器、操作符等等。在.net中,所有的類都最終繼承自system.object類,因此是一種引用型別,也就是說,new乙個類的例項時,例項的值儲存在託管堆

(managed heap)

中,而類的例項在堆疊(stack)上存放的是該例項在託管堆(managed heap)中的位址。

什麼是struct?

從上面的理解可以看出,class和struct最本質的區別是:

class是引用型別,而struct是值型別

,它們在記憶體中的分配情況有所不同。以下具體指出它們的不同之處:

1、class是引用型別,struct是值型別

既然class是引用型別,class可以設為null;而struct是值型別,不能設為null。

ortant; background-color: rgb(255, 255, 255);">ortant; font-size: 12px !important;">namespace

ortant; font-size: 12px !important;"> ax}}

ortant; font-size: 12px !important;">public

ortant; font-size: 12px !important;">struct

ortant; font-size: 12px !important;"> structa

ortant; font-size: 12px !important;">public

ortant; font-size: 12px !important;">class

ortant; font-size: 12px !important;"> classa

2、當例項化乙個class,它將建立在堆上;而例項化乙個struct,它將建立在棧上。

3、class的

使用是乙個對class例項的引用;而struct是直接使用它的值。例如:當我們將class作為引數傳遞給乙個方法,傳遞的是乙個引用,而struct傳遞的是值。

4、struct不能有初始化器;而class可以有初始化器。

ortant; background-color: rgb(255, 255, 255);">ortant; font-size: 12px !important;">public

ortant; font-size: 12px !important;">struct

ortant; font-size: 12px !important;"> structa

ortant; font-size: 12px !important;">public

ortant; font-size: 12px !important;">class

ortant; font-size: 12px !important;"> classa

5、class可以有無引數構造器;但是struct的構造器必須帶引數,而且必須初始化所有字段。

ortant; background-color: rgb(255, 255, 255);">ortant; font-size: 12px !important;">public

ortant; font-size: 12px !important;">struct

ortant; font-size: 12px !important;"> structa

ortant; font-size: 12px !important;">public structa(ortant; font-size: 12px !important;">int paraa) ortant; font-size: 12px !important;">//

ortant; font-size: 12px !important;">ok

ortant; font-size: 12px !important;">

}ortant; font-size: 12px !important;">public

ortant; font-size: 12px !important;">class

ortant; font-size: 12px !important;"> classa

}

6、類使用前必須用new關鍵字例項化;struct不需要。

7、class支援繼承和多型;struct不支援,但struct可以和類一樣實現介面。

8、既然struct不支援繼承,其成員不能以protected或internal修飾。

9、class比較適合較大的和複雜的資料;struct適用於作為經常使用的一些資料組合。

**:

C struct和class的比較

什麼是class?c 中的class 通常包含字段 屬性 方法 建構函式 索引器 操作符等等。在.net中,所有的類都最終繼承自system.object類,因此是一種引用型別,也就是說,new乙個類的例項時,例項的值儲存在託管堆 managed heap 中,而類的例項在堆疊 stack 上存放的...

C struct和class的區別

在c 中我們可以看到struct和class的區別並不是很大,兩者之間有很大的相似性。那麼為什麼還要保留struct,這是因為c 是向下相容的,因此c 中保留了很多c的東西。struct a 注意 因為struct是一種資料型別,那麼就肯定不能定義函式,所以在面向c的過程中,struct不能包含任何...

c struct和class的區別

1.struct不可以有無引數的建構函式 2.如果struct存在建構函式,所有屬性必須在建構函式中初始化 3.不可以在struct中直接初始化屬性 4.struct可以不使用new初始化 5.若struct沒有使用new初始化,所有屬性賦值之後,物件才可以使用 6.struct不可被繼承 7.st...