c#简单构造函数重载
本文关键字:重载 构造函数 简单 | 更新日期: 2023-09-27 18:05:30
我正在做一个非常简单的重载构造函数练习,但是我遇到了一个没有重载的参数。我以为我做得对,但也许我做错了什么?
namespace A3_Date_StudentWork
{
class MyDate
{
private int newMonth;
private int newDay;
private int currentMonth;
private int currentDay;
public MyDate(int month, int day)
{
newMonth = month;
newDay = day;
}
public MyDate(int month, int day, int cmonth, int cday)
{
newMonth = month;
newDay = day;
currentMonth = cmonth;
currentDay = cday;
}
}
}
下面是main
中新建对象的样子 MyDate today = new MyDate(todayMonth, todayDay);
MyDate bday = new MyDate(bdayMonth, bdayDay);
MyDate combine = new MyDate(bdayMonth, bdayDay, todayMonth, todayDay);
这是一个非常简单的程序,我所有的变量都是int。My整个Main:
static void Main(string[] args)
{
int todayMonth = 0;
int todayDay = 0;
int bdayMonth = 0;
int bdayDay = 0;
Console.WriteLine("What is today's month?");
Int32.TryParse(Console.ReadLine(), out todayMonth);
// Console.WriteLine(todayMonth);
Console.WriteLine("What is today's date?");
Int32.TryParse(Console.ReadLine(), out todayDay);
// Console.WriteLine(todayDay);
Console.WriteLine("What is your birth month?");
Int32.TryParse(Console.ReadLine(), out bdayMonth);
// Console.WriteLine(bdayMonth);
Console.WriteLine("What is your birth date?");
Int32.TryParse(Console.ReadLine(), out bdayDay);
// Console.WriteLine(bdayDay);
MyDate today = new MyDate(todayMonth, todayDay);
MyDate bday = new MyDate(bdayMonth, bdayDay);
MyDate combine = new MyDate(bdayMonth, bdayDay, todayMonth, todayDay);
这里是带有构造函数
的基类 {
class MyDate
{
private int newMonth;
private int newDay;
private int currentMonth;
private int currentDay;
public MyDate(int month, int day)
{
newMonth = month;
newDay = day;
}
public MyDate(int month, int day, int cmonth, int cday)
{
newMonth = month;
newDay = day;
currentMonth = cmonth;
currentDay = cday;
}
基类就是MyDate类
这里只是一个技术方面的建议。当您有多个构造函数时,如果可能的话,您应该通过传递值从一个构造函数调用另一个构造函数。这也被称为"构造函数链接"。
下面是基于你的代码的一个例子:
class MyDate
{
private int newMonth;
private int newDay;
private int currentMonth;
private int currentDay;
public MyDate(int month, int day)
: this(month, day, 0, 0)
{ }
public MyDate(int month, int day, int cmonth, int cday)
{
newMonth = month;
newDay = day;
currentMonth = cmonth;
currentDay = cday;
}
}
在这个简单的例子中,当你用2个参数(月和日)调用构造函数时,其他参数默认为0。你也可以使参数为空,这样你就可以给它分配一个空值。