我已经在网上访问了很多地方,但是找不到任何可以很好解释重载构造函数的东西。我只是在寻找一些指导
我必须在我的歌曲类中重载构造函数,以允许创建歌曲而无需提供copySold的值。
class Song
{
string name;
string artist;
int copiesSold;
public Song(string name, string artist, int copiesSold)
{
this.name = name;
this.artist = artist;
this.copiesSold = copiesSold;
}
public Song()
{
}
public string GetArtist()
{
return artist;
}
public string GetDetails()
{
return $"Name: {name} Artist: {artist} Copies Sold: {copiesSold},";
}
public string GetCertification()
{
if (copiesSold < 200000)
{
return null;
}
if (copiesSold < 400000)
{
return "Silver";
}
if (copiesSold < 600000)
{
return "Gold";
}
return "Platinum";
答案 0 :(得分:1)
必须使用 this 关键字来执行同一类的构造函数的调用,如下例所示
class Song
{
public string name;
string artist;
int copiesSold;
public Song(string name, string artist, int copiesSold)
{
this.name = name;
this.artist = artist;
this.copiesSold = copiesSold;
}
public Song():this("my_name","my_artist",1000)
{
}
}