using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace TestE
{


    class Employee
    {
        public string _name;
        public Employee(string name)
        {
            this._name = name;
            Console.Write ("Employee.CalculatePay:\n\t");
            CalculatePay ();
        }
        public virtual void CalculatePay()
        {
            Console.WriteLine ("Employee.CalculatePay called for {0}", _name);
        }
    }

    class SalariedEmployee : Employee
    {
        public decimal _salary;    
        public SalariedEmployee(string name, decimal salary) : base(name)
        {
            this._salary = salary;
            Console.Write ("SalariedEmployee.CalculatePay:\n\t");
            CalculatePay ();
        }
        public override void CalculatePay()
        {
            Console.WriteLine ("{0}, SalariedEmployee.CalculatePay, salary={1:C}", _name, _salary);
        }
    }

    class ContractEmployee : Employee
    {
        public double _rate;
        public ContractEmployee(string name, double rate) : base(name)
        {
            this._rate = rate;
            Console.Write ("ContractEmployee.CalculatePay:\n\t");
            this.CalculatePay ();

        }

        public override void CalculatePay()
        {
            Console.WriteLine ("{0}, ContractEmployee.CalculatePay, salary={1:C}", _name, _rate);
        }
    }

    class Program {
        static void Main(string[] args)
        {

            Employee[] employee = new Employee[2];
            employee[0] = new ContractEmployee("Ada" +
                "m Barr"123.45);

            Console.WriteLine ("");


            employee[1] = new SalariedEmployee(
                "Max Benson"67890m);

        }
    }
}



c++ 과는 다른 결과를 보인다, 생성자가 호출된 클래싀의 함수가 불리지 않고 virtual 로 선언된 경우 자식 함수가 불리게 된다




Employee.CalculatePay:

Adam Barr, ContractEmployee.CalculatePay, salary=₩0

ContractEmployee.CalculatePay:

Adam Barr, ContractEmployee.CalculatePay, salary=₩123


Employee.CalculatePay:

Max Benson, SalariedEmployee.CalculatePay, salary=₩0

SalariedEmployee.CalculatePay:

Max Benson, SalariedEmployee.CalculatePay, salary=₩67,890





반응형

+ Recent posts