zoukankan      html  css  js  c++  java
  • 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) { }
    }

  • 相关阅读:
    高质量图形库:pixellib
    有了 Docker,用 JavaScript 框架开发的 Web 站点也能很好地支持网络爬虫的内容抓取
    Freebie: Material Design UI Kit
    Git 10 周年之际,创始人 Linus Torvalds 访谈
    React.js 样式组件:React Style
    有趣 GIF 动图集
    10个免费开源的JS音乐播放器插件
    简约的单页应用引擎:sonnyJS
    2015年4月 非常干货之Python资源大全
    评论 ”[实例] 设计基于JQM的WebApp“
  • 原文地址:https://www.cnblogs.com/stevenxiao/p/443942.html
Copyright © 2011-2022 走看看