转:struct和class区别小结

本文详细阐述了结构体(struct)与类(class)之间的主要区别。包括它们的数据类型特性、继承能力、构造函数定义、默认初始化行为等方面,并强调了结构体作为值类型的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A struct is similar to a class, with the following major differences:

A class is a reference type, while a struct is a value type. Consequently, structs are typically used to express simple types, in which value-type semantics are desirable (e.g., assignment copies a value rather than a reference).

A class fully supports inheritance , whereas a struct can inherit only from an object and is implicitly sealed (in the runtime structs actually inherit from System.ValueType). Both classes and structs can implement interfaces.

A class can have a destructor, and a struct cannot.

A class can define a custom parameterless constructor and initialize instance fields, while a struct cannot. The default parameterless constructor for a struct initializes each field with a default value (effectively zero). If a struct declares a constructor(s), then all of its fields must be assigned in that constructor call.

结构具有以下特点:

  • 结构是值类型,而类是引用类型。
  • 向方法传递结构时,结构是通过传值方式传递的,而不是作为引用传递的。
  • 与类不同,结构的实例化可以不使用 new 运算符。
  • 结构可以声明构造函数,但它们必须带参数。
  • 一个结构不能从另一个结构或类继承,而且不能作为一个类的基。
  • 所有结构都直接继承自 System.ValueType,后者继承自 System.Object。
  • 结构可以实现接口。

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/changesway/archive/2008/10/28/3165141.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值