C#派生类构造函数

时间:2018-02-01 07:34:05

标签: c# visual-studio

我正在使用视频教程来学习C#;我认为这让我错了。我在哪里错了?

namespace BankAcct
{
    class Acct
    {
        private decimal balance;
        private string acctnum;

        // two constructor methods
        public Acct()
        {
            acctnum = "";
            balance = 0;
        }

        public Acct(string anum, decimal bal)
        {
            acctnum = anum;
            bal = balance;
        }
    } // end of Acct class

    // derived classes
    class CheckingAcct : Acct
    {
        // constructor
        public CheckingAcct(string anum, decimal bal) : base(acctnum, balance)
        {
            balance = bal;
            acctnum = anum;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Acct asacct = new Acct("666", 23.23);
            Console.ReadKey();
        }
    }
}

我正在使用Visual Studio社区。它在尝试调用派生类中的构造函数时会爆炸;关于私人数据成员无法访问的事情。我试图公开数据项,但没有用。

2 个答案:

答案 0 :(得分:1)

您无法使用在构造函数中设置的变量调用基本构造函数。 这样称呼:

//constructor
public CheckingAcct(string anum, decimal bal) : base(anum, bal)
{
}

答案 1 :(得分:0)

一些建议

    ...

    //DONE: better chain constructor then copy + paste
    // this("", 0) means Acct("", 0) i.e. acctnum = "" and balance = 0
    public Acct()
      : this("", 0) {
    }

    // This constructor assigns acctnum and balance fields 
    public Acct(string anum, decimal bal) {
      acctnum = anum;
      balance = bal; //DONE: Typo amended
    }

    ...

    //DONE: constructor chain is enough here: 
    //base class constructor - base(acctnum, balance) -
    // will assign acctnum and balance fields for you
    public CheckingAcct(string anum, decimal bal) 
      : base(anum, bal) {
      //DONE: you can't address private balance and acctnum fields there
    }