对于我的软件开发编程课程,我们应该为 RSS 提要制作一个“提要管理器”类型的程序。这是我如何处理 FeedItems 的实现。
很好很简单:
struct FeedItem {
string title;
string description;
string url;
}
我为此被标记了,“正确”的示例答案如下:
class FeedItem
{
public:
FeedItem(string title, string description, string url);
inline string getTitle() const { return this->title; }
inline string getDescription() const { return this->description; }
inline string getURL() const { return this->url; }
inline void setTitle(string title) { this->title = title; }
inline void setDescription(string description){ this->description = description; }
inline void setURL(string url) { this->url = url; }
private:
string title;
string description;
string url;
};
现在对我来说,这似乎很愚蠢。老实说,我不敢相信我被标记了,当这和我做的完全一样的事情时,我做的事情要多得多。
它让我想起在 C# 中人们总是这样做的:
public class Example
{
private int _myint;
public int MyInt
{
get
{
return this._myint;
}
set
{
this._myint = value;
}
}
}
我的意思是我知道他们为什么这样做,也许稍后他们想验证 setter 中的数据或在 getter 中增加它。但是,为什么你们不这样做,直到出现这种情况?
public class Example
{
public int MyInt;
}
抱歉,这是一种咆哮,而不是真正的问题,但冗余让我抓狂。为什么 getter 和 setter 在不需要的时候如此受欢迎?