我的代碼是在審查: https://codereview.stackexchange.com/questions/3754/c-script-could-i-get-feed-back/3755#3755C++朋友語法/語義問題
以下使用:
class Point
{
public:
float distance(Point const& rhs) const
{
float dx = x - rhs.x;
float dy = y - rhs.y;
return sqrt(dx * dx + dy * dy);
}
private:
float x;
float y;
friend std::istream& operator>>(std::istream& stream, Point& point)
{
return stream >> point.x >> point.y;
}
friend std::ostream& operator<<(std::ostream& stream, Point const& point)
{
return stream << point.x << " " << point.y << " ";
}
};
由另一個構件。我不明白朋友的功能在做什麼。有沒有另一種方法來做到這一點,而不使他們的朋友功能?客戶如何使用以下方式訪問他們?有人能說明究竟返回什麼嗎?
int main()
{
std::ifstream data("Plop");
// Trying to find the closest point to this.
Point first;
data >> first;
// The next point is the closest until we find a better one
Point closest;
data >> closest;
float bestDistance = first.distance(closest);
Point next;
while(data >> next)
{
float nextDistance = first.distance(next);
if (nextDistance < bestDistance)
{
bestDistance = nextDistance;
closest = next;
}
}
std::cout << "First(" << first << ") Closest(" << closest << ")\n";
}
@ Nawaz謝謝,我需要回顧一下Stroustrup的書。你瞭解正在返回的內容的語法嗎? –
@ Nawaz再次感謝,據說,我明白返回的類型,但它是返回這種類型的語義/功能。我假設stream >> point.x >> point.y從流構造函數中的文件讀入x和y成員變量。但爲什麼要退貨呢,爲什麼不把它留在那呢? –
@Matthew:你返回它表明你可以寫'stream << point1 << point2',也就是說,你可以在* chain *調用中使用它。 – Nawaz