이태홍
홍'story
이태홍
전체 방문자
오늘
어제
  • 분류 전체보기 (171)
    • TW (39)
    • AI (47)
      • 자연어 처리 (10)
      • Kaggle (2)
      • Machine Learning (26)
      • Computer Vision (0)
      • Deep Learning (0)
      • ROS2 (7)
    • Computer Science (29)
      • Data Structure (0)
      • Algorithm (18)
      • Computer Architecture (5)
      • SOLID (0)
      • System Programing (6)
    • LOLPAGO (10)
      • 프론트엔드 (10)
      • 백엔드 (0)
    • BAEKJOON (2)
    • React (5)
    • 언어 (8)
      • C++ (8)
    • GIT (0)
    • MOGAKCO (19)
    • 미국 여행기 (3)
    • etc. (7)
      • Blog (2)
      • 콜라톤 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 머신러닝
  • NLP
  • 딥러닝
  • kaggle
  • computer architecture
  • ML
  • Ai
  • 알고리즘
  • ROS2
  • LOLPAGO
  • algorithm
  • 백준
  • computerscience
  • tw
  • baekjoon
  • react
  • 경사하강법
  • 기계학습
  • pytorch
  • C++

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
이태홍

홍'story

[C++] 객체지향설계의 이해(실습)
언어/C++

[C++] 객체지향설계의 이해(실습)

2022. 10. 25. 15:46

🤔 객체지향설계의 이해 실습

이전에 포스팅한 내용을 바탕으로 실습을 진행해보겠습니다.

 

 

 

 

이론을 이해하고 실습을 하는 것을 추천하기 때문에 아래의 포스팅을 먼저 읽은 후에 실습을 진행하시는 것을 추천합니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

🔎 컴파일 에러 해결 1

 

📃 문제 

 

 

 

 

✏️ 해결

더보기

 

해설 : short 데이터 형은 32768을 나타낼 수 없기 때문에 int형으로 바꾸어 주어야 한다.

 

#include <iostream>

class LetDebug {
public:
	void printNum() {
		short s1 = 32767;
		short s2 = 1;
		int s3 = s1 + s2;

		std::cout << s3 << std::endl;

		std::cout << s1 << std::endl;
	}
};

int main() {
	LetDebug* Id = new LetDebug;
	Id->printNum();
	return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

🔎 Storage Duration

 

 

📃 문제

 

 

 

 

✏️ 해결

더보기

 

해석 : public을 선언하지 않으면 private으로 자동 선언된다.

 

main() 함수에서 Setvalue클래스의 변수에 직접 접근할 수 없기 때문에 컴파일 에러가 난다.

 

public을 선언해야 한다.

 

#include<iostream>

class SetValue
{
public:
	int x, y;
};

int main()
{
	SetValue obj; // 클래스이름 객체이름
	obj.x = 33;
	obj.y = 44;
    
	std::cout << "X = " << obj.x << " , Y = " << obj.y << std::endl;
    
	system("pause");
	return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

🔎 추상화 및 캡슐화

 

📃 문제

 

 

 

 

 

✏️ 해결

더보기

 

 해설 :  SetValue클래스의 지역변수 x, y가 private하게 선언되어 있으므로 해당 클래스의 메소드를 이용하여 변수에 접근하도록 한다.

 

즉, 추상화를 통해 해당 변수의 값을 변경한다.

 

#include<iostream>
class SetValue
{

	int x, y;

public:
	void setXY(int X, int Y) {
		x = X;
		y = Y;
	}


	void show() {
		std::cout << "X = " << x << " , Y = " << y << std::endl;
	}
};

int main()
{
	SetValue obj; // 클래스이름 객체이름
	
	obj.setXY(33, 44);
	obj.show();

	system("pause");
	return 0;
}

 

 

 

 

 

 

 

 

 

 

🔎 Method Overloading (C언어 vs C++)

 

📃 문제

 

 

 

 

✏️ 해결

더보기

 

해설 : C언어는 overloading을 허용하지 않지만 C++언어에서는 overloading을 허용하기 때문에 컴파일 에러가 발생하지 않는다.

 

 

 

 

C 언어

#include <stdio.h>
void print(int var)
{
	printf("Integer number: %d \n", var);
}
void print(float var)
{
	printf("Float number: %f \n", var);
}
void print(int var1, float var2)
{
	printf("Integer number: %d \n", var1);
	printf(" and float number: %f", var2);
}
int main()
{
	int a = 7;
	float b = 9;
	print(a);
	print(b);
	print(a, b);
	return 0;
}

// c에서는 에러가 난다. Overloading이 되지 않기 때문

 

 

 

 

C++

#include <stdio.h>
void print(int var)
{
	printf("Integer number: %d \n", var);
}
void print(float var)
{
	printf("Float number: %f \n", var);
}
void print(int var1, float var2)
{
	printf("Integer number: %d", var1);
	printf(" and float number: %f", var2);
}
int main()
{
	int a = 7;
	float b = 9;
	print(a);
	print(b);
	print(a, b);
	return 0;
}

// cpp에서는 에러가 나지 않는다. Overloading을 허용하기 때문

 

 

 

 

 

 

 

 

 

 

 

 

 

🔎 Stack

 

 

📃 문제

 

 

✏️ 해결

더보기

 

 해설 : stack을 구현합니당 

 

#include <iostream>
#define MAXSTACKSIZE 1000 // 스택의 최대 크기
class Stack {
	int top;
public:
	int a[MAXSTACKSIZE]; // 스택
	Stack() { top = -1; } // 스택의 꼭대기 값 초기화
	bool push(int x);
	int pop();
};
bool Stack::push(int x)
{
	if (top >= (MAXSTACKSIZE - 1)) {
		std::cout << "오류: 스택이 넘쳤습니다." << std::endl;
		return false;
	}
	else {
		// 코드 구현: 스택에 데이터 넣기
		
		a[++top] = x;

		std::cout << x << " 이 스택에 들어갔습니다." << std::endl;
		return true;
	}
}
int Stack::pop()
{
	if (top < 0) {
		std::cout << "오류: 스택이 비었습니다." << std::endl;
		return 0;
	}
	else {
		// 코드 구현 : 스택에서 데이터 빼기

		int x = a[top--];
		return x;
	}
}
int main()
{
	class Stack s;
	s.push(7);
	s.push(88);
	s.push(999);
	std::cout << s.pop() << " 을 스택에서 꺼냈습니다." << std::endl;
	std::cout << s.pop() << " 을 스택에서 꺼냈습니다." << std::endl;
	std::cout << s.pop() << " 을 스택에서 꺼냈습니다." << std::endl;
	system("pause");
	return 0;
}

 

🔎 

📃 문제

 

 

 

✏️ 해결

더보기

 

해설 :  random 함수를 호출하여 Dice 클래스의 지역변수인 value에 접근한다.

 

#include <iostream>
#include <ctime>
#include <cstdlib>
class Dice
{
	int value; // 주사위 값
public:
	void set_dice_value() // 주사위 값을 난수로 받을 수 있도록
	{
		/* 이 곳에 코드 추가 */
		value = rand() % 6 + 1;

	}
	int get_dice_value()
	{
		return value;
	}
};
int main()
{
	srand(time(NULL));
	Dice dice1;
	Dice dice2;
	dice1.set_dice_value();
	dice2.set_dice_value();
	std::cout << "두 주사위 합=" << dice1.get_dice_value() + dice2.get_dice_value() << std::endl;
	return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'언어 > C++' 카테고리의 다른 글

[C++] C++언어에서 지원하는 C언어의 문법  (0) 2022.10.26
[C++] Namespace  (0) 2022.10.26
[C++] 생성자/소멸자  (0) 2022.10.26
[C++] 클래스, 함수 오버로딩  (0) 2022.10.26
[C++] 객체지향설계의 이해(class, object, storage duration, abstraction, encapsulation, inheritance, polymorphism,)  (0) 2022.10.25
    '언어/C++' 카테고리의 다른 글
    • [C++] Namespace
    • [C++] 생성자/소멸자
    • [C++] 클래스, 함수 오버로딩
    • [C++] 객체지향설계의 이해(class, object, storage duration, abstraction, encapsulation, inheritance, polymorphism,)
    이태홍
    이태홍
    공부하자 태홍아

    티스토리툴바