gpt4 book ai didi

c# - 继承和构造函数中的错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:08 24 4
gpt4 key购买 nike

我目前正在研究一个涉及继承和构造函数的程序。我实际上是 C# 的新手,所以我只是想知道为什么下面的代码在第 57 行有错误,它说贷款不包含采用 0 个参数的构造函数。请帮我分析一下哪里出了问题。非常感谢。使用系统;

class DemoCarLoan3
{
static void Main()
{
Loan aLoan = new Loan(333, "Hanson", 7000.00);
CarLoan aCarLoan = new CarLoan(444, "Carlisle", 30000.00, 2011, "BMW");
Console.WriteLine("Loan #{0} for {1} is for Php{2}",
aLoan.LoanNumber, aLoan.LastName,
aLoan.LoanAmount.ToString("0,000.00"));
Console.WriteLine("Loan #{0} for {1} is for Php{2}",
aCarLoan.LoanNumber, aCarLoan.LastName,
aCarLoan.LoanAmount.ToString("0.00"));
Console.WriteLine(" Loan #{0} is for a {1} {2}",
aCarLoan.LoanNumber, aCarLoan.Year,
aCarLoan.Make);
Console.ReadLine();
}
}

class Loan
{
public const double MINIMUM_LOAN = 5000;
protected double loanAmount;
public int LoanNumber { get; set; }
public string LastName { get; set; }
public double LoanAmount
{
set
{
if (value < MINIMUM_LOAN)
loanAmount = MINIMUM_LOAN;
else
loanAmount = value;
}
get
{
return loanAmount;
}
}

public Loan(int num, string name, double amount)
{
LoanNumber = num;
LastName = name;
LoanAmount = amount;
}
}

class CarLoan : Loan
{
private const int EARLIEST_YEAR = 2006;
private const int LOWEST_INVALID_NUM = 1000;
private int year;

public CarLoan(int num, string name, double amount, int year, string make)
{
Year = year;
Make = make;
}

public int Year
{
set
{
if (value < EARLIEST_YEAR)
{
year = value;
loanAmount = 0;
}
else
year = value;
}
get
{
return year;
}
}

public string Make { get; set; }

public new int LoanNumber
{
get
{
return base.LoanNumber;
}
set
{
if (value < LOWEST_INVALID_NUM)
base.LoanNumber = value;
else
base.LoanNumber = value % LOWEST_INVALID_NUM;
}
}
}

最佳答案

只需添加对基本构造函数的调用

public CarLoan(int num, string name, double amount, int year, string make) 
: base(num, name, amount)
{
Year = year;
Make = make;
}

当您在不调用基类构造函数的派生类中声明构造函数时,它会自动调用那里不存在的具有 0 个参数的构造函数。如果您按原样使用代码,它将编译为

public CarLoan(int num, string name, double amount, int year, string make) 
: base()
{
Year = year;
Make = make;
}

但这是无效的,因为基类中没有参数为 0 的构造函数。因此,要么创建一个,要么调用现有的一个。

关于c# - 继承和构造函数中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20717224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com