• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
愛如風過
我想到一个地方,那里最好一年下2次雨,1次下半年!
博客园    首页    新随笔    联系   管理    订阅  订阅
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) { }
}

posted on 2006-07-06 09:48  愛如風過  阅读(269)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3