对于练习,我必须创建一个各种各样的库.项目规范表明应该有一个类Book和Borrower字段:
+---------------------------+ +--------------------------+
|Book | |Borrower |
+---------------------------+ +--------------------------+
|private string title | |private string name |
|private string author | |private Book b |
|private int ISBN |
Run Code Online (Sandbox Code Playgroud)
和这些方法:
|public Book(string,string,int)| |public Borrower(String) |
|public string GetAuthor() | |public string GetName() |
|public string GetTitle() | |public Book GetBook() |
|public int GetISBN() | |public void SetBook(Book)|
|// add methods, if needed | | |
+------------------------------+ +-------------------------+
Run Code Online (Sandbox Code Playgroud)
所以我把它编码到我的编译器中,但是在我的Borrower课程中我有错误,如:
class Borrower
{
private string name;
private Book b;
public Borrower(string n)
{
name = n;
}
public string GetName()
{
return name;
}
public Book GetBook()
{
return b;
}
public void SetBook(Book) //I get an error here (Identifier expected)
{
Book = b; // error here says Book is type but is used as a variable
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Book班级,这里没有错误
class Book
{
private string title, author;
private int ISBN;
public Book(string a, string b, int c)
{
title = a;
author = b;
ISBN = c;
}
public string GetAuthor()
{
return author;
}
public string GetTitle()
{
return title;
}
public int GetISBN()
{
return ISBN;
}
}
Run Code Online (Sandbox Code Playgroud)
我是否得到错误,因为我有一个与类名相同的方法 Book,或者我可以将该类实际用作方法吗?
这种方法
public void SetBook(Book)
{
Book = b;
}
Run Code Online (Sandbox Code Playgroud)
应改写如下:
public void SetBook(Book b)
{
this.b = b;
}
Run Code Online (Sandbox Code Playgroud)
否则,作为参数传递的对象将没有名称.我使用了与您的字段相同的名称Book b,因此我添加this.b了消除歧义.