1 minute read

03-1. 구조체 안에 함수 정의하기

  • 코드
#include<iostream>
using namespace std;

/// <summary>
/// 구조체 내에서 함수 정의하기
/// DefFuncInStruct.cpp
/// </summary>

struct Point {
	int xpos;
	int ypos;

	void MovePos(int x, int y) {
		xpos += x;			//구조체 내에서 함수가 정의되어 있으므로 변수에 접근할 수 있다
		ypos += y;			//구조체 default 접근지시레이블은 private	
	}

	void AddPoint(const Point& pos) {
		xpos += pos.xpos;
		ypos += pos.ypos;
	}

	void ShowPosition() {
		cout << "[" << xpos << "," << ypos << "]" << endl;

	}
};


int main(void) {
	Point pos1 = { 12,4 };
	Point pos2 = { 20,30 };

	pos1.MovePos(-7, 10);
	pos1.ShowPosition();

	pos1.AddPoint(pos2);
	pos1.ShowPosition();
	return 0;
}

03-2.클래스의 정의

1번: 계산기

  • 💻코드
#include<iostream>
using namespace std;

class Calculator {
private:
	int add_c, min_c, div_c, mul_c;

public:
	void Init();
	double Add(double a, double b);
	double Min(double a, double b);
	double Div(double a, double b);
	double Mul(double a, double b);
	void ShowOpCount();
};

void Calculator::Init() {
	add_c = 0, min_c = 0, div_c = 0, mul_c = 0;
}

double Calculator::Add(double a, double b) {
	add_c++;
	return a + b;
}

double Calculator::Min(double a, double b) {
	min_c++;
	return a - b;
}

double Calculator::Mul(double a, double b) {
	mul_c++;
	return a * b;
}

void Calculator::ShowOpCount() {
	cout << "덧셈: " << add_c << " ";
	cout << "뺄셈: " << min_c << " ";
	cout << "곱셈: " << mul_c << " ";
	cout << "나눗셈: " << div_c << " ";
}

double Calculator::Div(double a, double b) {
	div_c++;
	return a / b;
}

int main(void) {
	Calculator cal;
	cal.Init();
	cout << "3.2 + 2.4 = " << cal.Add(3.2, 2.4) << endl;
	cout << "3.5 / 1.7 = " << cal.Div(3.5, 1.7) << endl;
	cout << "2.2 - 1.5 = " << cal.Min(2.2, 1.5) << endl;
	cout << "4.9 / 1.2 = " << cal.Div(4.9, 1.2) << endl;
	cal.ShowOpCount();
	return 0;
	
}

2번: 프린터

  • 💻코드
#include<iostream>
#include<string>
using namespace std;

class Printer {
private:
	string strbox;

public:
	void SetString(string str);
	void ShowString();
};

void Printer::SetString(string str) {
	strbox.erase();
	strbox.append(str);

}

void Printer::ShowString() {
	cout << strbox <<endl;

}

int main(void) {
	Printer pnt;
	pnt.SetString("Hello world!");
	pnt.ShowString();

	pnt.SetString("I love c++");
	pnt.ShowString();

	return 0;
}

문제는 쉽고, 어차피 답은 교재 뒤에 다 나와있다
익히기 위해 한번씩 연습해보는 용도로 나쁘지 않음

Tags: ,

Categories:

Updated: