내 코드에 검토되었다 https://codereview.stackexchange.com/questions/3754/c-script-could-i-get-feed-back/3755#3755은 C++을 친구 구문/의미 질문
다음 사용 :
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