PP.249 MyFriendClass.cpp
//Boy.h
#ifndef __BOY_H__
#define __BOY_H__
#include "Girl.h"
class Boy
{
private:
int height;
friend class Girl; // Girl클래스에 대한 friend 선언
public:
Boy(int len);
void ShowYourFriendInfo(Girl& frn);
};
#endif // !__BOY_H__
//Boy.cpp
#include <iostream>
#include <cstring>
#include "Boy.h"
using namespace std;
Boy::Boy(int len) : height(len) {}
void Boy::ShowYourFriendInfo(Girl& frn)
{
cout << "소녀의 전화번호 : " << frn.phoneNum << endl;
}
//Girl.h
#ifndef __GIRL_H__
#define __GIRL_H__
#include "Boy.h"
class Girl
{
private:
char phoneNum[20];
friend class Boy; // Boy클래스에 대한 friend 선언
public:
Girl(const char* phnum);
void ShowYourFriendInfo(Boy& frn);
};
#endif // !__GIRL_H__
//Girl.cpp
#include <iostream>
#include <cstring>
#include "Girl.h"
using namespace std;
Girl::Girl(const char* phnum)
{
strcpy(phoneNum, phnum);
}
void Girl::ShowYourFriendInfo(Boy& frn)
{
cout << "소년의 키 : " << frn.height << "cm" << endl;
}
// main.cpp
#include <iostream>
#include <cstring>
#include "Boy.h"
#include "Girl.h"
using namespace std;
int main()
{
Boy boy(170);
Girl girl("010-123-4567");
boy.ShowYourFriendInfo(girl);
girl.ShowYourFriendInfo(boy);
return 0;
}
PP. 252 MyFriendFunction.cpp
#include <iostream>
#include <cstring>
using namespace std;
class Point;
class PointOP
{
private:
int opcnt;
public:
PointOP(): opcnt(0) {}
Point PointAdd(const Point&, const Point&);
Point PointSub(const Point&, const Point&);
~PointOP()
{
cout << "동작 회수 : " << opcnt << endl;
}
};
class Point
{
private:
int x;
int y;
public:
Point(const int& xpos, const int& ypos) : x(xpos), y(ypos) {}
friend Point PointOP::PointAdd(const Point&, const Point&);
friend Point PointOP::PointSub(const Point&, const Point&);
friend void ShowPointPos(const Point&);
};
Point PointOP::PointAdd(const Point& pt1, const Point& pt2)
{
opcnt++;
return Point(pt1.x + pt2.x, pt1.y + pt2.y);
}
Point PointOP::PointSub(const Point& pt1, const Point& pt2)
{
opcnt++;
return Point(pt1.x - pt2.x, pt1.y - pt2.y);
}
int main()
{
Point pos1(1, 2);
Point pos2(3, 4);
PointOP op;
ShowPointPos(op.PointAdd(pos1, pos2));
ShowPointPos(op.PointSub(pos1, pos2));
return 0;
}
void ShowPointPos(const Point& pos)
{
cout << "x : " << pos.x << endl;
cout << "y : " << pos.y << endl;
}
'PROGRAM > C++' 카테고리의 다른 글
Visual Studio 2019 community Secure Warning 무시하기 (0) | 2021.03.09 |
---|---|
CH5. 문자열 분할 (0) | 2020.08.20 |
4. 프로그램 및 데이터 구조화 -2 (0) | 2020.08.18 |
CH04. 프로그램 및 데이터 구조화 (0) | 2020.08.17 |
CH03. 데이터 일괄처리 (0) | 2020.08.17 |