3、編寫控制檯應用程序,設計一個普通職工類Employee,其工資爲基本工資(1000)加上工齡工資(每年增加30元)。從Employee類派生一個本科生類UEmployee,其工資爲普通職工算法的1.5倍,另從Employee類派生一個研究生類SEmployee,其工資爲普通職工算法的2倍,要求計算工資用虛方法實現;分別用相關數據進行測試。
using System;
namespace Test3_3
{
public class Employee
{
private double bsalary = 1000;
private double psalary;
private int n;
public int Pn
{
get { return n; }
set { n = value; }
}
public virtual double ComSalary()
{
Console.Write("工作年數:");
Pn = int.Parse(Console.ReadLine());
psalary = bsalary + 30 * Pn;
return psalary;
}
public class UEmployee : Employee
{
new public double ComSalary()
{
return 1.5 * base.ComSalary();
}
}
public class GEmployee : Employee
{
public override double ComSalary()
{
return 2 * base.ComSalary();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("普通職工:");
Employee emp1 = new Employee();
Console.WriteLine("該普通職工的工資爲:{0}", emp1.ComSalary());
Console.WriteLine("本科生職工:");
UEmployee emp2 = new UEmployee();
Console.WriteLine("本科生職工的工資爲:{0}", emp2.ComSalary());
//Console.WriteLine("研究生職工:");
GEmployee emp3 = new GEmployee();
Console.WriteLine("研究生職工的工資爲:{0}", emp3.ComSalary());
}
}
}
}
運行結果:
4、設計控制檯應用程序,假設圖書館的圖書類Book包含書名、編號和作者屬性,讀者類Reader包含姓名和借書證屬性,每位讀者最多可借5本書,設計它們的公共基類BClass。要求列出所有讀者的借書情況,類似下圖所示:
using System;
namespace Test3_4
{
public class BClass // 基類
{
private string name; // 名稱
private int no; // 編號
public BClass( string na, int n) // 構造函數
{
name = na;
no = n;
}
public void show()
{
Console.Write( "{0}({1})" , name, no);
}
}
public class Book : BClass // 圖書類
{
string author; // 作者
public Book( string na, int n, string auth) : base(na, n)
{
author = auth;
}
public void showBook()
{
base.show();
Console .Write( " 作者 :{0}" , author);
}
}
public class Reader : BClass // 讀者類
{
Book[] rent; // 所借圖書
int top;
public Reader( string na, int n) : base(na, n) // 構造函數
{
rent = new Book[5];
top = 0;
}
public void rentBook( ref Book b)
{
rent[top] = b;
top++;
}
public void showReader()
{
Console.Write( "讀者 :" );
base.show();
Console .WriteLine( " 所借圖書 :" );
for ( int i = 0; i < top; i++)
{
Console .Write( " {0}:" , i + 1); //5 個空格
rent[i].show();
Console .WriteLine();
}
}
}
class Program
{
static void Main(string[] args)
{
Book b1 = new Book( "C語言 ", 100, " 潭浩強 ");
Book b2 = new Book( "數據結構 ", 110, "嚴蔚敏 " );
Book b3 = new Book( "軟件工程 ", 210, "陳華 ");
Book b4 = new Book( "操作系統 ", 208, "張明 ");
Reader r1 = new Reader( "王華 ", 1234);
Reader r2 = new Reader( "李兵 ", 2600);
r1.rentBook( ref b1);
r1.rentBook( ref b2);
r1.rentBook( ref b3);
r2.rentBook( ref b4);
r1.showReader();
r2.showReader();
}
}
}
運行結果: