[英]How can I give the proper return type for this function c++?
我的教授給了我們程序模板,並希望我們填寫他給我們的原型的功能,但我在如何正確返回這個日期 function 時遇到問題。
這是 Movie class 模板,它實例化了一個 const Date releaseDate;
class Movie
{
public:
-->// all of "name(name), releaseDate(Date(yyyy, mm, dd)) {}" is what I added to the constructor, I think that is the only way I can
// properly instantiate Date because he said Date releaseDate must be constant.
Movie(string & name, int yyyy, int mm, int dd) : name(name), releaseDate(Date(yyyy, mm, dd)) {};
Date & getReleaseDate();
// other?
bool operator== (Movie &);
Movie & operator++();
friend ostream & operator<<(ostream &, Movie &);
friend ostream & operator<<(ostream &, const Movie &);
private:
Movie();
const Date releaseDate;
string name;
int rating;
};
這是日期 class 模板
class Date
{
public:
Date(int, int, int);
//….
// other as appropriate
bool operator==(Date &);
friend ostream & operator<<(ostream &, const Date &);
private:
int day, month, year;
};
然后這是我認為應該正確的 Date 的重載 << 運算符
ostream & operator << (ostream & os, const Date & dt)
{
os << dt.month << "/" << dt.day << "/" << dt.year << "\n";
return os;
}
約會時我唯一遇到的問題是我如何打電話
Date & Movie::getReleaseDate()
{
cout << releaseDate;
return releaseDate;
}
cout << 重載 function 並沒有給我任何錯誤,但是因為它說 getReleaseDate() 必須返回一些東西,所以我必須返回,但是當我嘗試返回 releaseDate 時,它說“返回:不能從 const Date 轉換為 Date &" 那么我需要進行哪些更改才能使其正常工作? 我有點困惑。
擁有像releaseDate
這樣的const
成員會限制您。 例如,您的 class 不再可分配。 通常我會建議讓你的私有數據成員保持非const
——你總是可以只公開一個不可變的公共接口。
無論如何,您都必須這樣做。 您不能返回對const
事物的可變引用。 您的getReleaseDate()
應該返回const Date&
或Date
(副本)。
現在, function 本身也可以是const
,以便它適用於const Movie
。
它也不應該執行 output; 這不是“錯誤”,但這是出乎意料的,而不是您的 class 的用戶一定想要的。 如果他們想這樣做,他們總是可以這樣做cout << movie.getReleaseDate()
。
你的operator<<
。
在這里盡量避免使用“模板”這個詞。 我知道你的意思,但“模板”是指 C++ 中的特定內容,不是這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.