【发布时间】:2019-10-14 21:45:59
【问题描述】:
我在标题中遇到错误,谁能告诉我我的代码有什么问题?
public class Book
{
public string Distributor { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
public double Price { get; set; }
public Book(string distributor, string name, int amount, double price)
{
this.Distributor = distributor;
this.Name = name;
this.Amount = amount;
this.Price = price;
}
public override string ToString()
{
string line = string.Format("| {0,15} | {1,15} | {2,5} | {3,6} |", Distributor, Name, Amount, Price);
return line;
}
public override bool Equals(object obj)
{
Book book = obj as Book;
return book.Price == Price;
}
public override int GetHashCode()
{
return Price.GetHashCode();
}
public static Book operator >= (Book book1, Book book2) //the error here
{
Book temp = new Book();
if (book1.Name == book2.Name && book1.Price > book2.Price)
temp = book1;
return temp;
}
public static Book operator <= (Book book1, Book book2) // and here
{
Book temp = new Book();
if (book1.Name == book2.Name && book1.Price < book2.Price)
temp = book2;
return temp;
}
}
我在“操作员”行中遇到错误。我希望运算符 '>=' 和 '
【问题讨论】:
-
您没有接受零参数的 Book 构造函数。编译器的错误信息中明确说明。
-
我需要什么构造器?
-
您需要一个空的构造函数 public Book() { } 通常这个空的构造函数是自动定义的,但是当您创建自己的构造函数时,它就不会再自动添加了
-
>=和<=运算符应该返回bool,而不是Book。这也应该解决您的构造函数问题,因为您不会在运算符内部创建一本书。