friend

๋‘๊ฐœ์˜ ํด๋ž˜์Šค๊ฐ€ ์žˆ์„ ๋•Œ, ์„œ๋กœ ๋งŒ๋“ค์–ด์ง„ ๋ชจ๋“  ๋ฉค๋ฒ„๋ณ€์ˆ˜, ๋ฉค๋ฒ„ํ•จ์ˆ˜๋ฅผ ๊ณต์œ ํ•˜๊ธฐ ์œ„ํ•ด์„œ ์šฐ๋ฆฌ๋Š” friend ๋ผ๋Š” ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

a ๊ฐ์ฒด๊ฐ€ b ๊ฐ์ฒด๋ฅผ ์นœ๊ตฌ๋กœ ์„ ์–ธํ•œ๋‹ค๋ฉด b๊ฐ์ฒด๋Š” a๊ฐ์ฒด์˜ ๋ชจ๋“  ๋ณ€์ˆ˜์™€ ํ•จ์ˆ˜๊ฐ’์„ ๊ฐ–๋‹ค๊ฐ€ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

privateย ๊นŒ์ง€ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค!!!!

#include <iostream>

using namespace std;

class Point{
private:
    int x;
    int y;

    
    
public:
    Point(): x(0), y(0){}
    Point(int _x, int _y): x(_x), y(_y) {}
    
    void setXY(int _x, int _y){
        this->x = _x;
        this->y = _y;
    }
    
    int getX() const { return this->x; }
    int getY() const { return this->y; }
    
    Point operator + (Point& pt){
        Point result(this->x + pt.x, this->y + pt.y);
        return result;
    }
    
    Point operator - (Point& pt){
        Point result(this->x - pt.x, this->y - pt.y);
        return result;
    }
    
    Point operator = (Point& pt){
        this->x = pt.x;
        this->y = pt.y;
        return (*this);
    }
    
    // SpyPoint์— Point ํด๋ž˜์Šค์˜ ๋ชจ๋“  ์ •๋ณด๋ฅผ ๋„˜๊ฒจ์ค€๋‹ค.
    friend class SpyPoint;
};

class SpyPoint{
public:
    void print_all_point_info(Point& pt){
        cout << "SpyPoint์— ์˜ํ•ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค." << endl;
        cout << "x : " << pt.x << endl;
        cout << "y : " << pt.y << endl;
    }
};


int main(){
    Point pt1(1, 2), pt2(3, 4);
    
    SpyPoint spyPt;
    spyPt.print_all_point_info(pt1);
    spyPt.print_all_point_info(pt2);

    return 0;
}
Output
SpyPoint์— ์˜ํ•ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.
x : 1
y : 2
SpyPoint์— ์˜ํ•ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.
x : 3
y : 4
Program ended with exit code: 0