Struct Constructor Restrictions

Struct Constructor Restrictions
Although the syntax for struct and class constructors is the same, there are some
additional restrictions that apply to struct constructors:
1. The compiler always creates a default struct constructor.
         The compiler always generates a default constructor, regardless of whether you
         declare constructors yourself.
2. You cannot declare a default constructor in a struct.
          The reason for this restriction is that the compiler always creates a default
          constructor in a struct (as just described) so you would end up with a duplicate
          definition.
          You can declare a struct constructor as long as it expects at least one argument.
3. You cannot declare a protected constructor in a struct.
         The reason for this restriction is that you can never derive other classes or
         structs from a struct, and so protected access would not make sense, as shown
        in the following example:
class CPoint
{
// Okay
protected CPoint(int x, int y) { ... }
}
struct SPoint
{
// Compile-time error
protected SPoint(int x, int y) { .. . }
}
4. You must initialize all fields.
 class CPoint
{
private int x, y;
public CPoint(int x, int y) { /*nothing*/ }
// Okay. Compiler ensures that x and y are initialized to
// zero.
}
However, if you declare a struct constructor that fails to initialize a field, the
compiler will generate a compile-time error:
struct SPoint1 // Okay: initialized when declared
{
private int x = 0, y = 0;
public SPoint1(int x, int y) { }
}
struct SPoint2 // Okay: initialized in constructor
{
private int x, y;
public SPoint2(int x, int y)
{
this.x = x;
this.y = y;
}
}
struct SPoint3 // Compile-time error
{
private int x, y;
public SPoint3(int x, int y) { }
}

转载于:https://www.cnblogs.com/stevenxiao/archive/2006/07/06/443942.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值