C++ (3월 7일 ~ 3월 8일)


Solution : 응용 프로그램

Project : 실행 파일 (.exe)

하나의 솔루션이 있으면 그 안에는 여러 개의 프로젝트가 존재함.

프로젝트 안에는 .exe 파일이 존재함. (.exe 파일은 기계어)

sln : 솔루션 디렉토리를 의미

proj : 프로젝트를 의미

콘솔 창에서는 텍스트 메시지만 출력 가능

솔루션을 시작 프로그램으로 설정 해야 다른 솔루션을 실행하지 않음


#include <iostream>

int main() {
	std::cout << "Hello2";
	return 0;
}


Hello.cpp (소스코드) 을 Hello.obj (목적 코드) 로 바꿈 (컴파일) 그 다음 Hello.exe 수행

소스 코드를 목적 코드로 바꾸는 것을 컴파일이라고 함

목적 코드에 resource 가 추가 되어야 .exe 파일을 만들 수 있음 ==> link 라고 함

Build (빌드) : Compile + link

하나의 프로젝트 혹은 여러 개의 프로젝트를 한꺼번에 빌드할 수 있음


디버그란 무엇인가?

프로그램 상에서 존재하는 오류를 버그라 칭하고, 그 버그를 없애는 것을 디버그라고 함.


/* 
	소스: SimpleC++.cpp
	cout과 << 연산자를 이용하여 화면에 출력한다.
*/

#include <iostream> // cout과 << 연산자 포함 // preprocessor (전처리) ==> 프로그램을 컴파일할 때 컴파일 직전에 실행되는 별도의 프로그램.

// C++ 프로그램은 main() 함수에서부터 실행을 시작한다.
int main() {
	std::cout << "Hello\n"; // 화면에 Hello를 출력하고 다음 줄로 넘어감 // std : standard // 덕분에 cout는 어느 운영체제에서도 적용 가능 (ex: 리눅스, 윈도우, 등등..)
	std::cout << "첫 번째 맛보기입니다."; // cout 는 문자열을 받아가지고 사용자의 console로 뿌려주는 객체 // << : 연산자 (오버로딩) (C에서는 의미가 달라짐)
	return 0; // main() 함수가 종료하면 프로그램이 종료됨
}

// main() 으로 시작해 main()이 끝나면 프로그램이 종료됨 // \n : 제어 문자 (프로그램이 컴퓨터에 지시함)


C++ (수강 정정) (3월 7일 ~ 3월 8일)


수강 정정으로 인해 처음부터 다시..


This course is about:

  • 실세계의 문제를 Object 로 모델링하여 나타내고 객체를 표현하는데 필요한 자료구조와 그에 대한 연산을 모아 Class 로 나타냄.

  • Data Abstraction and Information Hiding

  • Derived Class 를 통해 한 Class 가 가지고 있는 자료구조와 연산 등의 속성을 다른 Class 에 전달하는 Inheritance

  • 가상함수를 활용한 Polymorphism (다형성) 의 구현

  • 연산자가 객체의 종류에 따라 다른 의미를 갖도록 하는 Operator Overloading (연산자 중복)

  • Class 가 특정 자료형에 종속되는 경향을 완화하기 위한 Template


About the course:

  • Textbook
    • Introduction to Programming with C++ 3ED, Liang
  • Sub-Textbook
    • C++ Primer Plus
  • Quizs & homework assignments

  • Exams
    • 1 Midterms & 1 Final
  • Cheating policy : zero tolerance


Visual Studio 2022 Install

  1. Select “New Project”
  2. Select an empty project C++
  3. Enter your project name at the designated folder
  4. Click RB on the Source file
  5. Select C++ file, and name it main.cpp
  6. Write down your codes for main.cpp, and save
  7. Click “Rebuild solution” under Build menu
  8. Check success meaning no syntax error
  9. Click “Start w/o debugging” under Debug menu


Chap 01, Chap 02 : C++ Standard IO

  1. C++ Program basic components
  2. Understanding #include
  3. Understanding namespace와 std::
  4. Standard out
  5. Standard in


// main.cpp

#include <iostream> 

using namespace std;

int main() {
	cout << "Hello\n"; /* 화면에 Hello를 출력하고 다음 줄로 넘어감 */
	cout << World.";
	return 0; 
}


Basic C++ Program


  • comments

    • 여러 줄 주석문 - /* … */

    • 한 줄 주석문 - //


  • main() 함수
    • 프로그램의 실행을 시작하는 함수
    • main()에서 return문 생략 가능


  • #include <iostream>
    • C++ Preprocessor에게 내리는 지시
    • <iostream> 헤더 파일을 컴파일 전에 소스에 확장하도록 지시
  • <iostream> 헤더 파일
    • 표준 입출력을 위한 클래스와 객체, 변수 등이 선언됨


  • cout 객체
    • 표준 C++ 출력 스트림 객체
    • <iostream> 헤더 파일에 선언
  • « 연산자
    • stream insertion operator
    • 오른쪽 피연산자를 왼쪽 스트림 객체에 삽입
    • cout 객체에 연결된 화면에 출력
    • 여러 개의 « 연산자로 여러 값 출력 가능


std::cout << "Hello\n" << "World.";


« 연산자 활용


  • 문자열 및 기본 타입의 데이터 출력
int n = 3;
char c = '#';
std::cout << c << 5.5 << '-' << n << "hello" << true; // false;를 입력하면 0 출력

실행 결과 :

#5.5-3hello1


다음 줄로 넘어갈 때는 \n or endl 조작자 사용 !!


cout and « 를 이용한 화면 출력

#include <iostream>
double area(int r); // 함수의 원형 선언
int main() {
	int n=3;
	char c='#';
	std::cout << c << 5.5 << '-' << n << "hello" << true << std::endl;
	std::cout << "n + 5 = " << n + 5 << '\n'; 
	std::cout << "면적은 " << area(n); // 함수 area()의 리턴 값 출력
}
double area(int r) { // 함수 구현
	return 3.14*r*r; // 반지름 r의 원면적 리턴
}


namespace 개념


  • identifier 충돌이 발생하는 경우
    • 여러 명이 서로 나누어 프로젝트를 개발하는 경우
    • 오픈 소스를 가져와서 컴파일을 하거나 링크하는 경우
  • namespcae 키워드
    • 충돌 해결
    • 개발자가 자신만의 이름 공간을 생성할 수 있도록 함
  • 이름 공간 생성 및 사용
namespcae alpha { // alpha라는 이름 공간 생성
 ...... // 이 곳에 선언된 모든 이름은 alpha 이름 공간에 생성된 이름

}


std:: 개념


  • std
    • ANSI C++ 표준에서 정의한 namespace 중 하나
    • 모든 C++ 표준 라이브러리는 std namespace에 만들어져 있음
  • std 생략
    • 생략하고 싶으면 using 지시어 사용 !

ex_

using namespace std; 
...................
cout << "Hello" << endl; // std:: 생략 !


C++ 에서 키 입력 받기


#include <iostream> 
using namespace std;
int main() {
	cout << "너비를 입력하세요: ";
	int width;
	cin >> width; // 키보드로부터 너비를 읽어 width 변수에 저장
	cout << "높이를 입력하세요: ";
	int height;
	cin >> height; // 키보드로부터 높이를 읽어 height 변수에 저장
	int area = width*height;	 // 사각형의 면적 계산
	cout << "면적은 " << area << "\n"; // 면적을 출력하고 다음 줄로 넘어감
} 

실행 결과 :

너비를 입력하세요: 3
높이를 입력하세요: 5
면적은 15


Cpp 에서 입출력은 cin + cout 를 이용한다는 것을 기억하자.


실행문 중간에 변수 선언


  • C++ 변수 선언은 아무 곳이나 가능

ex_

int width;
cin >> width; // 키보드로부터 너비를 읽는다.
cout << "높이를 입력하세요: ";
int height;
cin >> height; // 키보드로부터 높이를 읽는다.
// 너비와 높이로 구성되는 사각형의 면적을 계산한다.
int area = width*height;
cout << "면적은 " << area << "\n"; // 면적을 출력하고 한 줄 띈다.


C++ 문자열 표현 방식


  1. C-스트링 방식 – ‘\0’로 끝나는 문자 배열
  2. string 클래스 이용

string 클래스 방식이 훨씬 효율적.

#include <string> 클래스를 통해서 선언해야 하는데,

애초에 #include <iostream> 에 내장되어 있는 클래스라 굳이 X

근데 평소에 써두는 연습해두면 좋음


ex_

#include <iostream>
#include <cstring>
using namespace std;
int main() {
	char password[11];
	cout << "프로그램을 종료하려면 암호를 입력하세요." << endl;
	while(true) {
		cout << "암호: ";
		cin >> password;
		if(strcmp(password, "C++") == 0) {
			cout << "프로그램을 정상 종료합니다." << endl;
			break;
		}
		else 
			cout << "암호가 틀립니다~~" << endl;
	}
}

실행 결과 :

프로그램을 종료하려면 암호를 입력하세요.
암호: Java
암호가 틀립니다~~
암호: C
암호가 틀립니다~~
암호: C++
프로그램을 정상 종료합니다.


cin.getline() 을 이용한 문자열 입력


  • 공백이 포함된 문자열을 입력 받는 방법
  • cin.getline(char buf[], int size, char delimitChar)
    • buf에 최대 size-1개의 문자 입력. 끝에 ‘\0’ 붙임
    • delimitChar를 만나면 입력 중단. 끝에 ‘\0’ 붙임
      • delimitChar의 디폴트 값은 ‘\n’(<Enter>키)


<iostream> 헤더 파일은 어디에?


  • <iostream> 파일은 텍스트 파일
  • 컴파일러가 설치된 폴더 아래 include 폴더에 존재
    • ex_ C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include


cin , cout 는 어디에 선언되어 있는가?


  • cin , cout → 모두 <iostream>에 선언된 객체 !!!


#include <헤더파일> , #include "헤더파일"


결론부터 말하면 둘의 주요한 차이점은 해당 헤더파일이 존재하는 경로의 차이이다.


  • #include <헤더파일>
    • ‘헤더파일’을 찾는 위치
      • 컴파일러가 설치된 폴더에서 찾으라는 지시

ex_

#include <iostream> 헤더 파일 → 컴파일러가 기본적으로 제공


  • #include “헤더파일”
    • 개발자의 프로젝트 폴더
    • 개발자가 만든 헤더 파일이나 추가로 외부 라이브러리를 포함하고 싶은 경우 위와 같은 명령을 사용해야 한다.

해당 헤더 파일이 존재하는 경로에 따라 알맞게 사용해주도록 하자 !!!


Tips


  • Input buffer를 flush할 때의 명령어


  • Visual Studio 2012이하
    • fflush(stdin);


  • Visual Studio 2015 이상
    • cin.clear();
    • cin.ignore();



## C++ (3월 14일)


seperator → space

키 값이 전달 됐다 → 변수가 존재한다.


cin cout 예제 (SimpleInput)

#include <iostream>

using namespace std;

int main() {

	cout << "Width : ";
	int w;
	cin >> w;

	cout << "Height : ";
	int h;
	cin >> h;

	int area = w * h;
	cout << "면적은 " << area << " 입니다." << endl; 

	return 0;
}


맨 마지막 문자가 ‘\0’ 이어야 문자열이 선언 된다.

아니라면 그냥 단순 문자 배열.


ex_

char name2[5] = {‘G’, ‘r’, ‘a’, ‘c’, ‘e’}; → 단순 문자 배열


C-string ex_


strcmp() 함수를 쓰기 위해서는 #include <cstring>이라는 헤더 파일을 선언 해줘야 한다.

strcmp() → 문자열 비교 함수 !


Password 예제


#include <iostream>

using namespace std;

int main() {

	cout << "암호를 입력하세요 : " << endl;
	char pwd[100];

	while (true) {

		cout << "암호 : ";
		cin >> pwd;
		if (strcmp(pwd,"C++") == 0) {
			cout << "프로그램을 정상 종료합니다." << endl;
			break;

		}

		else {
			cout << "암호가 틀립니다! " << endl;

		}

	}

	return 0;

}


<iostream> 헤더 파일은 어디에?


iostream 파일을 메모장으로 열어보자.


// iostream standard header

// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#pragma once
#ifndef _IOSTREAM_
#define _IOSTREAM_
#include <yvals_core.h>
#if _STL_COMPILER_PREPROCESSOR
#include <istream>

#pragma pack(push, _CRT_PACKING)
#pragma warning(push, _STL_WARNING_LEVEL)
#pragma warning(disable : _STL_DISABLED_WARNINGS)
_STL_DISABLE_CLANG_WARNINGS
#pragma push_macro("new")
#undef new
_STD_BEGIN
#ifdef _M_CEE_PURE
__PURE_APPDOMAIN_GLOBAL extern istream cin;
__PURE_APPDOMAIN_GLOBAL extern ostream cout;

cin, cout 등이 존재하는 걸 알 수 있다 !!


C++ (3월 15일)


Defining a Function


용어 외우기) parameters

정해진 구역에서만 reference 되는 것들을 지역변수라고 한다.

  • Function siggnature is the combination of the function name and the parameter list.

    • function name
    • number of parameters
    • type of parameters
    • return type and pass-by-ref are not part of Function Signature (중요)

함수의 signature 만 다르면 똑같은 이름의 함수 선언 가능 ..


function Overloading

  • multiple functions can use the same name
  • When the function name is the same but the signature is different, these functions are different functions that can be overloaded

하나의 scope 안에 동일한 이름의 함수를 선언 가능 .. ! (signature가 다를 때)

즉 parameter 의 data type 이 다르면 된다..


int VariableReturnType( char c, int i);
double VariableReturnType( char c, int i); // Error


void SameSignature( int i );
void SameSignature( int& r );
...
int i = 10;
SameSignature( i );			// Error


Scope of Variables


  • A local variable (parameter 포함): a variable defined inside a function
  • Scope : the part of the program where the variable can be referenced


Pass by Value

  • When you invoke a function with a parameter, the value of the argument is passed to the parameter.
    • If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter.
    • The argument variable is not affected, regardless of the changes made to the parameter inside the function.


pass by value의 핵심 ) 본 변수에 아무 영향 없음


Reference Vars (매우 중요함) (농담 아님)


Alias : Wakgood 으로 가자


Reference Vars 예제


#include <iostream>

using namespace std;

int main() {

	int target = 20;

	int& ref = target;

	cout << "ref : " << ref << endl;
	cout << "target : " << ref << endl;
	cout << "ref : " << &ref << endl;
	cout << "target : " << &target << endl;

	ref = 200;

	cout << "ref : " << ref << endl;
	cout << "target : " << ref << endl;

	return 0;
}


// 제출하는 숙제 아님

#include <iostream>

using namespace std;

void swap_passbyvalue(int x, int y);

int main() {
	int i, j;
	// i, j prompt 를 주고 입력 받는다.
	// 입력된 값을 출력한다. 
	// i, j 값을 swap_passbyvalue 에 전달 및 invoke (call) 한다.
	// i, j 값을 출력한다.
	

	return 0; 
}

void swap_passbyvalue(int x, int y); {
	int temp = x;
	x = y;
	y = temp;

}


C++ 첫 과제 solution


#include <iostream>
#include <cstring>

using namespace std;

int main() {

	char addr[100];

	cout << "** 주소 입력 없이 엔터를 누를 경우 프로그램이 종료 됩니다 **" << endl;

	// 숙제 아래와 같이 아래의 5번 라인과 9번 라인 같이 주소를 계속 입력받아
	// 출력한다. 단 사용자가 주소입력 없이 엔터만 치면 프로그램을 종료한다.

	while (true) {

		cout << "주소를 입력하세요 : ";

		cin.getline(addr, 100);

		if (strcmp(addr, "") == 0) {

			break;

		}

		else {

			cout << "주소는 " << addr << " 입니다." << endl;

			continue;


		}

		

	}

	return 0;+

}


## C++ (3월 21일)


Ch6. functions

reference 변수는 메모리 영역을 공유한다.

call by reference = &

Reference variable itself does not reserve mem space. (무조건 상기할 것)

  • C++ provides a special type of variable, called a reference variable
  • can be used as a function parameter to reference the original variable.
  • A reference variable is an alias for another variable
  • Any changes made through the reference variable are actually performed on the original variable.
  • To declare a reference variable, place the ampersand (&) in front of the name.


매개변수 개수, 매개변수의 Data type, 함수의 이름 (무조건 상기할 것)


#include <iostream>
using namespace std;
void sub(int i, int& r); // 이때 &의 역할은 pass by reference
void swap_PassByValue(int x, int y);
void swap_PassByRef(int& x, int& y);
// void swap_PassByPtr(int* xp, int* yp);
int main() {
	/*int a = 1, b = 2;

	cout << "address of a : " << &a << endl;
	cout << "address of b : " << &b << endl;

	sub(a, b);*/

	int i, j;
	cout << "i의 값 : "; 
	cin >> i;
	cout << "j의 값 : ";
	cin >> j;
	cout << "address of i : " << &i << endl;
	cout << "address of j : " << &j << endl;
	swap_PassByValue(i, j); // 변경 X
	cout << "i : " << i << " j : " << j << endl;
	swap_PassByRef(i, j); // 변경 O
	cout << "i : " << i << " j : " << j << endl;
	return 0;
}
void sub(int i, int& r) {
	cout << "address of i : " << &i << endl;
	cout << "address of r : " << &r << endl;
	i = 100;
	r = 200;

}

void swap_PassByValue(int x, int y) {
	cout << "address of x : " << &x << endl;
	cout << "address of y : " << &y << endl;
	int temp = x;
	x = y;
	y = temp;
}

void swap_PassByRef(int& x, int& y) {
	cout << "address of x : " << &x << endl;
	cout << "address of y : " << &y << endl;
	int temp = x;
	x = y;
	y = temp;
}

실행결과

i의 값 : -5
j의 값 : 70
address of i : 0000005A453EF7B4
address of j : 0000005A453EF7D4
address of x : 0000005A453EF790
address of y : 0000005A453EF798
i : -5 j : 70
address of x : 0000005A453EF7B4
address of y : 0000005A453EF7D4
i : 70 j : -5

빌드 - 구성관리자 - 플랫폼을 win32 로 변경 후 실행결과

i의 값 : -5
j의 값 : 70
address of i : 012FFBE8
address of j : 012FFBDC
address of x : 012FFB04
address of y : 012FFB08
i : -5 j : 70
address of x : 012FFBE8
address of y : 012FFBDC
i : 70 j : -5


homework _ 6.33 ! p.287 (이번주 일요일)

Ch 7 : Array (내일까지 ㅋㅋㅋㅋ 아..) Ch 11 : pointer, array&pointer → 중요


C++ does not check array’s boundary. So, accessing array elements using subscripts beyond the boundary does not cause syntax errors..

element 접근 시 상수가 아니라 변수가 와도 된다~


C++ (3월 22일)


Pass-by-Value?


A = B;

안 되는 이유 → A는 배열의 첫 번째 주소인 상수이기 때문..


int A[3] = {5,8,-7};
int B[3] = {-5, -8, 70};

double d = 58.7;
double D[3] = {7.7, 8.8, 99.99}
32 bits !!
메모리 컨텐츠는 4개의 비트 단위로 만들어짐.


#include <iostream>

using namespace std;

int main() {
	int A[3] = { 10,20,30 };
	int B[3] = { -7, -8, 99 };
	double C[3] = { 5.7, 8.8, 2.1 };
	char D[] = { 'H', 'e', 'l', 'l', 'o'};
	char E[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
	cout << "sizeof(int) : " << sizeof(int) << endl;
	cout << "sizeof(double) : " << sizeof(double) << endl;
	cout << "sizeof(char) : " << sizeof(char) << endl;
	cout << "sizeof(A) : " << sizeof(A) << endl;
	cout << "sizeof(B) : " << sizeof(B) << endl;
	cout << "sizeof(C) : " << sizeof(C) << endl;
	cout << "sizeof(D) : " << sizeof(D) << endl;
	cout << "sizeof(E) : " << sizeof(E) << endl;


	return 0;
}

실행 결과_

sizeof(int) : 4
sizeof(double) : 8
sizeof(char) : 1
sizeof(A) : 12
sizeof(B) : 12
sizeof(C) : 24
sizeof(D) : 5
sizeof(E) : 6

물론 실행 결과의 플랫폼은 win32 기준이다.


#include <iostream>

using namespace std;

int main() {
	int A[3] = { 10,20,30 };
	int B[3] = { -7, -8, 99 };
	double C[3] = { 5.7, 8.8, 2.1 };
	char D[] = { 'H', 'e', 'l', 'l', 'o'};
	char E[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
	cout << "sizeof(int) : " << sizeof(int) << endl;
	cout << "sizeof(double) : " << sizeof(double) << endl;
	cout << "sizeof(char) : " << sizeof(char) << endl;
	cout << "sizeof(A) : " << sizeof(A) << endl;
	cout << "sizeof(B) : " << sizeof(B) << endl;
	cout << "sizeof(C) : " << sizeof(C) << endl;
	cout << "sizeof(D) : " << sizeof(D) << endl;
	cout << "sizeof(E) : " << sizeof(E) << endl;
	cout << "A : " << A << endl; // 배열 A의 0번째 요소의 현재 메모리 컨텐츠 시작 주소가 나온다 ,,
	cout << "&A[0] : " << &A[0] << endl;
	cout << "&A[1] : " << &A[1] << endl;


	return 0;
}

실행 결과_

sizeof(int) : 4
sizeof(double) : 8
sizeof(char) : 1
sizeof(A) : 12
sizeof(B) : 12
sizeof(C) : 24
sizeof(D) : 5
sizeof(E) : 6
A : 004FF8D4
&A[0] : 004FF8D4
&A[1] : 004FF8D8

&A[0] → &A[1] 의 차이는 4 !!!


#include <iostream>

using namespace std;

int main() {
	int A[3] = { 10,20,30 };
	int B[3] = { -7, -8, 99 };
	double C[3] = { 5.7, 8.8, 2.1 };
	char D[] = { 'H', 'e', 'l', 'l', 'o'};
	char E[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
	cout << "sizeof(int) : " << sizeof(int) << endl;
	cout << "sizeof(double) : " << sizeof(double) << endl;
	cout << "sizeof(char) : " << sizeof(char) << endl;
	cout << "sizeof(A) : " << sizeof(A) << endl;
	cout << "sizeof(B) : " << sizeof(B) << endl;
	cout << "sizeof(C) : " << sizeof(C) << endl;
	cout << "sizeof(D) : " << sizeof(D) << endl;
	cout << "sizeof(E) : " << sizeof(E) << endl;
	cout << "A : " << A << endl; // 배열 A의 0번째 요소의 현재 메모리 컨텐츠 시작 주소가 나온다 ,,
	cout << "&A[0] : " << &A[0] << endl;
	cout << "&A[1] : " << &A[1] << endl;
	cout << "C : " << C << endl; 
	cout << "&C[0] : " << &C[0] << endl;
	cout << "&C[1] : " << &C[1] << endl;



	return 0;
}

실행 결과_

sizeof(int) : 4
sizeof(double) : 8
sizeof(char) : 1
sizeof(A) : 12
sizeof(B) : 12
sizeof(C) : 24
sizeof(D) : 5
sizeof(E) : 6
A : 008FFB0C
&A[0] : 008FFB0C
&A[1] : 008FFB10
C : 008FFAD8
&C[0] : 008FFAD8
&C[1] : 008FFAE0


#include <iostream>

using namespace std;

int main() {
	int A[3] = { 10,20,30 };
	int B[3] = { -7, -8, 99 };
	double C[3] = { 5.7, 8.8, 2.1 };
	char D[] = { 'H', 'e', 'l', 'l', 'o'};
	char E[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
	cout << "sizeof(int) : " << sizeof(int) << endl;
	cout << "sizeof(double) : " << sizeof(double) << endl;
	cout << "sizeof(char) : " << sizeof(char) << endl;
	cout << "sizeof(A) : " << sizeof(A) << endl;
	cout << "sizeof(B) : " << sizeof(B) << endl;
	cout << "sizeof(C) : " << sizeof(C) << endl;
	cout << "sizeof(D) : " << sizeof(D) << endl;
	cout << "sizeof(E) : " << sizeof(E) << endl;
	cout << "A : " << A << endl; // 배열 A의 0번째 요소의 현재 메모리 컨텐츠 시작 주소가 나온다 ,,
	cout << "&A[0] : " << &A[0] << endl;
	cout << "&A[1] : " << &A[1] << endl;
	cout << "C : " << C << endl; 
	cout << "&C[0] : " << &C[0] << endl;
	cout << "&C[1] : " << &C[1] << endl;
	cout << "D : " << D << endl;
	cout << "&D[0] : " << &D[0] << endl;
	cout << "&D[1] : " << &D[1] << endl;

	return 0;
}

실행 결과_

sizeof(int) : 4
sizeof(double) : 8
sizeof(char) : 1
sizeof(A) : 12
sizeof(B) : 12
sizeof(C) : 24
sizeof(D) : 5
sizeof(E) : 6
A : 008FF71C
&A[0] : 008FF71C
&A[1] : 008FF720
C : 008FF6E8
&C[0] : 008FF6E8
&C[1] : 008FF6F0
D : Hello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
&D[0] : Hello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
&D[1] : ello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆

이렇게 결과가 나온 이유


char ptr 배열의 경우 cout를 만나면

해당하는 배열의 주소에서 시작하는 문자열이 왔구나 !!

하고 생각하고 문자열을 출력하게 됨 ,,,

solution __ 형 변환을 하자 ….


#include <iostream>

using namespace std;

int main() {
	int A[3] = { 10,20,30 };
	int B[3] = { -7, -8, 99 };
	double C[3] = { 5.7, 8.8, 2.1 };
	char D[] = { 'H', 'e', 'l', 'l', 'o'};
	char E[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
	cout << "sizeof(int) : " << sizeof(int) << endl;
	cout << "sizeof(double) : " << sizeof(double) << endl;
	cout << "sizeof(char) : " << sizeof(char) << endl;
	cout << "sizeof(A) : " << sizeof(A) << endl;
	cout << "sizeof(B) : " << sizeof(B) << endl;
	cout << "sizeof(C) : " << sizeof(C) << endl;
	cout << "sizeof(D) : " << sizeof(D) << endl;
	cout << "sizeof(E) : " << sizeof(E) << endl;
	cout << "A : " << A << endl; // 배열 A의 0번째 요소의 현재 메모리 컨텐츠 시작 주소가 나온다 ,,
	cout << "&A[0] : " << &A[0] << endl;
	cout << "&A[1] : " << &A[1] << endl;
	cout << "C : " << C << endl; 
	cout << "&C[0] : " << &C[0] << endl;
	cout << "&C[1] : " << &C[1] << endl;
	cout << "D : " << D << endl;
	cout << "&D[0] : " << &D[0] << endl;
	cout << "&D[1] : " << &D[1] << endl;
	cout << "(void *)E : " << (void *)E << endl;
	cout << "(void *)&E[0] : " << (void*)&E[0] << endl;
	cout << "(void *)&E[1] : " << (void*)&E[1] << endl;

	return 0;
}

실행 결과_

sizeof(int) : 4
sizeof(double) : 8
sizeof(char) : 1
sizeof(A) : 12
sizeof(B) : 12
sizeof(C) : 24
sizeof(D) : 5
sizeof(E) : 6
A : 0056FA7C
&A[0] : 0056FA7C
&A[1] : 0056FA80
C : 0056FA48
&C[0] : 0056FA48
&C[1] : 0056FA50
D : Hello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
&D[0] : Hello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
&D[1] : ello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
(void *)E : 0056FA28
(void *)&E[0] : 0056FA28
(void *)&E[1] : 0056FA29


char E[] = "Hello";
위의 E  6byte 잡아먹음 ,, 


중요 (농담아님)


#include <iostream>

using namespace std;

int funcMin(int A[], int size);
void copyArr(int To[], int From[], int size);
void printArr(int A[], int size);

int main() {

	int A[3] = { 10,20,30 };
	int B[3] = { -7, -8, 99 };
	double C[3] = { 5.7, 8.8, 2.1 };

	cout << "A 배열의 최소값 : " << funcMin(A, 3) << endl;
	copyArr(A, B, 3);
	printArr(A, 3);

	char D[] = { 'H', 'e', 'l', 'l', 'o'};
	char E[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

	cout << "sizeof(int) : " << sizeof(int) << endl;
	cout << "sizeof(double) : " << sizeof(double) << endl;
	cout << "sizeof(char) : " << sizeof(char) << endl;

	cout << "sizeof(A) : " << sizeof(A) << endl;
	cout << "sizeof(B) : " << sizeof(B) << endl;
	cout << "sizeof(C) : " << sizeof(C) << endl;
	cout << "sizeof(D) : " << sizeof(D) << endl;
	cout << "sizeof(E) : " << sizeof(E) << endl;

	cout << "A : " << A << endl; 
	/* 배열 A의 0번째 요소의 현재 메모리 컨텐츠 시작 주소가 나온다 ,,,, */
	cout << "&A[0] : " << &A[0] << endl;
	cout << "&A[1] : " << &A[1] << endl;

	cout << "C : " << C << endl; 
	cout << "&C[0] : " << &C[0] << endl;
	cout << "&C[1] : " << &C[1] << endl;

	cout << "D : " << D << endl;
	cout << "&D[0] : " << &D[0] << endl;
	cout << "&D[1] : " << &D[1] << endl;

	cout << "(void *)E : " << (void *)E << endl;
	cout << "(void *)&E[0] : " << (void*)&E[0] << endl;
	cout << "(void *)&E[1] : " << (void*)&E[1] << endl;

	return 0;
}

int funcMin(int K[], int size) {
	cout << "K in funcMin() : " << K << endl;
	int min = K[0];
	for (int i = 0; i < size; i++) {
		if (min > K[i]) {
			min = K[i];

			}

		}
	return min;
}

void copyArr(int To[], int From[], int size) {
	for (int i = 0; i < size; i++) {
		To[i] = From[i];
	}
}

void printArr(int A[], int size) {
	for (int i = 0; i < size; i++) {
		cout << A[i] << " ";

	}

	cout << endl;

}

실행 결과_

K in funcMin() : 00B5FDD0
A 배열의 최소값 : 10
-7 -8 99
sizeof(int) : 4
sizeof(double) : 8
sizeof(char) : 1
sizeof(A) : 12
sizeof(B) : 12
sizeof(C) : 24
sizeof(D) : 5
sizeof(E) : 6
A : 00B5FDD0
&A[0] : 00B5FDD0
&A[1] : 00B5FDD4
C : 00B5FD9C
&C[0] : 00B5FD9C
&C[1] : 00B5FDA4
D : Hello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
&D[0] : Hello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
&D[1] : ello儆儆儆儆儆勁儆儆?@슇솛솛!@蠱儆儆
(void *)E : 00B5FD7C
(void *)&E[0] : 00B5FD7C
(void *)&E[1] : 00B5FD7D


7.1 ~ 7.2 checkpoint 실습


Chapter 11 (Pointers, relationship … )


&11.5 까지 읽고 와야 됨 ,,,,,

checkpoint → 반드시 강의를 듣고 실습할 것

포인터도 배열이기 때문에 메모리를 가져야 함 …


What is Pointer ?


Pointer variables, simply called pointers, are designed to hold memory addresses as their values. 

Normally, a variable contains a specific value, e.g., an integer, a floating-point value, and a character. 

However, a pointer contains the memory address of a variable that in turn contains a specific value. 


Memory 뿐만 아니라 Pointer 역시 파악할 수 있어야 함


## C++ (3월 29일)


Ex_0633 Solution

#include <iostream>
using namespace std;


bool solveEquation(double a, double b, double c, double d,
    double e, double f, double& x, double& y);
int main()
{
  double a, b, c, d, e, f, x, y;
  bool isSolvable;
  cout << "Enter a, b, c, d, e, f: ";
  cin >> a >> b >> c >> d >> e >> f;

  isSolvable = solveEquation(a, b, c, d, e, f, x, y);

  if (isSolvable)
    cout << "x is " << x << " and y is " << y << endl;
  else
    cout << "The equation has no solution" << endl;

  return 0;
}
bool solveEquation(double a, double b, double c, double d,
    double e, double f, double& x, double& y)
{
    double detA = a * d - b * c; // local variable
    bool isSolvable; // local variable
    if (detA == 0) {
        isSolvable = false;
    }
    else
    {
        x = (e * d - b * f) / detA;
        y = (a * f - e * c) / detA;
        isSolvable = true;
    }
    return isSolvable;
}


3월 29일 소스 코드


#include <iostream>

using namespace std;

int main() {

	int a = 123;
	int* ip = &a;

	char c = 'p';
	char* cp = &c;

	cout << "&a : " << &a << endl;
	cout << "&ip : " << &ip << endl;
	cout << "ip : " << ip << endl;
	cout << "*ip : " << *ip << endl;
	cout << "&c : " << (void*)&c << endl;
	cout << "&cp : " << (void*)&cp << endl;
	cout << "cp : " << (void*)cp << endl;
	cout << "*cp : " << *cp << endl;

	return 0;
}


숙제 → 319p 7.7 , 7.8

rand() 함수를 사용하기 위해서는 #include <cstdlib> 추가..

7.8 에서 const 생략


C++ (3월 30일)


void pointer


항상 포인트 변수에는 타입 정보를 줘야함

더블 포인터는 8바이트

쇼트 포인터면 2바이트를 읽어야 됨

포인터 정보만 갖고 있고 타입이 없는 포인터는 void*


7_7

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {

	int num[25], sum = 0;
	int random_integer;
	for (int i = 0; i < 25; i++) {

		num[i] = (rand()%25) + 0;
	}

	cout << "랜덤 숫자 결과 : " << endl;

	for (int i = 0; i < 25; i++)

	{
		cout << num[i] << " ";

		if (num[i] % 2 == 0)
			sum += num[i];
	}

	cout << "짝수 정수의 합계 : " << sum << endl;

}


7_8

#include <iostream>
using namespace std;

double product(const double array[], int size);
int product(const int array[], int size);

int main()
{
	int s1;
	int s2;
	double ar[10];
	int arr[10];

	cout << "더블 타입 배열의 사이즈를 입력하세요 ! " << endl;

	cin >> s1;

	cout << "요소를 더블 타입 배열로 입력하세요 ! " << endl;

	for (int i = 0; i < s1; i++)
	{
		cin >> ar[i];
	}
	double p = product(ar, s1);

	cout << "더블 타입 배열 요소의 곱은 :  " << p << endl;
	cout << "int 타입 배열 크기를 입력하세요 ! : " << endl;

	cin >> s2;

	cout << "int 타입 배열에 요소를 입력 : " << endl;

	for (int i = 0; i < s2; i++)
	{
		cin >> arr[i];
	}

	int pr = product(arr, s2);
	cout << "int 타입 배열 요소의 곱은 : " << pr << endl;

	return 0;
}

double product(const double array[], int size)
{
	double p = 1;

	for (int i = 0; i < size; i++)
	{
		p = p * array[i];
	}
	return p;
}
int product(const int array[], int size)
{
	int p = 1;

	for (int i = 0; i < size; i++)
	{
		p = p * array[i];
	}
	return p;
}


C++ (Midterm Exam)


중간고사 → 필기 위주

  • cin, cout을 포함하는 파일
  • &A[0] 와 같은 의미인 표현을 고르시오
  • 스택 메모리 구조 그리기 (중요)
  • 주소값 구하는 문제
  • 포인터 표현이 잘못된 것 고르기
  • 데이터 타입


Write a program that first read an integer for the array size, then reads characters into the array, and displays the consonants
#include <iostream>

bool is_consonant(const char * c)
{
    char consonant[] = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz";
    if (strpbrk(c, consonant) != NULL)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    char* arr = nullptr;
    int arr_size = 0;


    int size = 0;
    std::cout << "Enter size of array : ";
    std::cin >> size;
    for (int i = 0; i < size; i++)
    {
        std::cout << "Enter symbol number " << i + 1 << " : ";
        char tmp[2];
        std::cin >> tmp;
        if (is_consonant(tmp))
        {
            char* tmp_arr = new char[arr_size + 1];
            for (int j = 0; j < arr_size; j++)
            {
                tmp_arr[j] = arr[j];
            }
            tmp_arr[arr_size] = tmp[0];


            delete[]arr;
            arr = tmp_arr;
            arr_size++;
        } 
    }
    for (int i = 0; i < arr_size; i++)
    {
        std::cout << arr[i] << "\t";
    }
    std::cout << std::endl;

    system("pause");
    return 0;
}


C++ (4월 5일)


#include <iostream>
using namespace std;
const int MAX = 10;
int* dyIntArr(int n);

int main() {

	int A[MAX] = { 999 }; // static 메모리 allocation
	cout << "A : " << A << " *(A+0) : " << *(A + 0) << endl;
	cout << "&A[0] : " << &A[0] << endl;
	int size = 0;
	
	cout << "&size : " << &size << endl;
	cout << "how many elements? : ";
	cin >> size;

	// int* B = new int[size]; // dynamic memory allocation, on heap
	int* B = dyIntArr(size); // 얘가 41라인 받음

	for (int i = 0; i < size; i++) {

		cout << "입력 : ";
		cin >> *(B + i);
	}
	cout << "&B : " << &B << endl;
	cout << "B : " << B << " *(B+0) : " << *(B + 0) << endl;
	// 합을 구해서 평균을 계산한 후 출력한다.
	int  total = 0;
	for (int i = 0; i < size; i++) {
		total += *(B + i);
	}

	cout << "총합 : " << total << endl;
	cout << "평균 : " << total / size << endl;
	delete[] B;
	B = NULL;

	return 0;
}

int* dyIntArr(int n) {
	int* p = new int[n];
	return 0;
}

Excel & 11.2 풀어오기



C++ (4월 11일)


Ex_11_02

#include <iostream>
#include <cctype>
using namespace std;

int main()
{
  // Prompt the user to enter array size
  cout << "Enter array size: ";
  int arraySize;
  cin >> arraySize;

  char* numbers = new char[arraySize];
  int size = 0;

  for (int i = 0; i < arraySize; i++)
  {
        // Read and store character in an array if it is not a vowel
        cout << "Enter a character: ";
        char ch;
        cin >> ch;

        bool isVowel = false;

          if (tolower(ch) == 'a' || tolower(ch) == 'e' || tolower(ch) == 'i' || tolower(ch) == 'o' || tolower(ch) == 'u')
          {
            isVowel = true;
          }

        if (!isVowel)
        {
          *(numbers + size) = ch;
          size++;
        }
  }

  if(size == 0)
  {
      cout << "There are no consonants in the array!" << endl;
      return 0;
  }

  for (int i = 0; i < size; i++)
    cout << *(numbers + i) << " ";

  return 0;
}



스택의 메모리는 아래로 내려갈 수록 증가함

먼저 선언 → 맨 밑으로 이동


Ch09


int A[5] = {999,0,0,0,0,0};
char B[5] = "MEMO";

cout << A << endl; --> 0번째 요소의 주소값을 출력한다.

*(A+0) 

>>>
cout 은 특이하게 char * (포인터) 가 오면 문자열을 출력한다
int, del, 같은 포인터는 주소를 출력하는데 ..
cout << (void *) B << endl; 라고 해야 주소가 출력됨 !! 


size&(A)
20 (4bytes * 5)
size&(B)
5 (1bytes * 5)


리버스 → func() 에서 함 main() 이 아니라

그러나 해지와 사용은 main() 에서

다이나믹 알로케이션은 함수와 함수를 넘나들 수 있는 특성이 있음


C++ (4월 12일)


member variable = member field


컴파일러는 함수를 3가지로 함수를 구분 : 함수를 구분하기 위한 구성요소를 시그너처(signature)라 한다.

Signature 구성 하는 것 3가지

  • 이름
  • Parameter 개수
  • Parameter data type


Return 값이 없을 때는 Void 를 써야 하는데

교수님이 보여준 함수는 객체가 생성될 때 (메모리 확보)

member variable을 초기화 하기 위한 특수 목적을 갖고 있기 때문에 void 와 반환 (return) 둘 다 없어도 됨..


Class 는 기본적으로 기능을 제공하는 것임.

라이브러리를 파는 것 = Class 를 만들어서 파는 것 (Class는 일종의 서버 역할)

UML 넘어감


function = method

Class is a Type


Constructor 계수와 deconstructor 계수가 같은지 반드시 확인해야 한다.

ExCircle


#include <iostream>
using namespace std;
class Circle {
public:
	double radius; // Member Variable
	double getArea(); // Member Function
	Circle(); // Constructor without argument
	Circle(double r); // Constructor with argument
	~Circle(); // deconstructor
};
double Circle::getArea() {
	return 3.14 * radius * radius;
}
Circle::Circle() {
	cout << "Constructor without arguement" << endl;
	radius = 1;
} 
Circle::Circle(double r) {
	cout << "Constructor with arguement" << endl;
	radius = r;
}
Circle::~Circle() {

	cout << "deconstructor without arguement" << endl;
}
int main() {
	cout << "sizeof(Circle) : " << sizeof(Circle) << endl;
	Circle c1;
	cout << "sizeof(c1) : " << sizeof(c1) << endl;
	cout << "c1.getArea() : " << c1.getArea() << endl;
	Circle c2(10);
	cout << "c2.getArea() : " << c2.getArea() << endl;
	return 0;
}
sizeof(Circle) : 8
Constructor without arguement
sizeof(c1) : 8
c1.getArea() : 3.14
Constructor with arguement
c2.getArea() : 314
deconstructor without arguement
deconstructor without arguement



C++ (4월 18일)


main.cpp

#include <iostream>
#include "Circle.h"
using namespace std;


int main() {
	cout << "sizeof(Circle) : " << sizeof(Circle) << endl;
	Circle c1;
	cout << "sizeof(c1) : " << sizeof(c1) << endl;
	cout << "c1.getArea() : " << c1.getArea() << endl;
	Circle c2(10);
	cout << "c2.getArea() : " << c2.getArea() << endl;
	return 0;
}


Circle.cpp

#include <iostream>
#include "Circle.h"
using namespace std;

double Circle::getArea() {// Member function
	return radius * radius * 3.14;
}
Circle::Circle() {// constructor without arg
	cout << "constructor without arg" << endl;
	radius = 1;
}
Circle::Circle(double r) {// constructor with arg
	cout << "constructor with arg" << endl;
	radius = r;
}
Circle::~Circle() {// deconstructor
	cout << "deconstructor" << endl;
}


Circle.h

#ifndef Circle_H
#define Circle_H
class Circle {
public:
	double radius;    // Member variable
	double getArea(); // Member function
	Circle(); // constructor without arg
	Circle(double r); // constructor with arg
	~Circle(); // deconstructor
};
#endif


C++ (4월 19일)

Constructor → member variables 초기화

10-1,2 X

usually use call by ref


int main() {
	Circle obj(50);
	cou << "&obj : " << &obj << endl;
	printCircleByVal(obj);
	printCircleByRef(obj);

    return 0;
}

void printCircleByVal(Circle c) {
	cout << "&c : " << &c << endl;
	cout << " The area of the Circle : " << c.getArea() << endl;
}
void pritnCircleByRef(Circle& c) {
	cout << "&c : " << &c << endl;
	cout << " The area of the Circle : " << c.getArea() << endl;
}


int main() {
Circle obj(50);
cout << "&obj : " << &obj << endl;
printCircleByVal(obj);
printCircleByRef(obj);

return 0;
}

void printCircleByVal(Circle c) {
	cout << "&c : " << &c << endl;
	cout << " The area of the Circle : " << c.getArea() << endl;
}

void pritnCircleByRef(Circle& c) {
	cout << "&c : " << &c << endl;
	cout << " The area of the Circle : " << c.getArea() << endl;
}

void printCircleByPtr(Circle C) {

	cout << "&C : " << &c << endl;
	cout << "The area of the Circle : " << (*c).getArea() << endl;
	cout << "The area of the Circle : " << c -> getArea() << endl;

}



C++ (5월 9일)


Hotdog Stand


HD.h

#ifndef HD_H
#define HD_H
//hotdogs.cpp
//This program defines a class for tracking hot dog sales.
//
//It tracks the stand's ID number, hot dogs sold at each stand,
//  and hot dogs sold at all stands.

class HotDogStand
{
public:
	HotDogStand();
	HotDogStand(int newID, int newNnumSold);
	int GetID();
	void SetID(int newID);
	void JustSold();
	int GetNumSold();
private:
	int numSold;
	int ID;

public:
	static int GetTotalSold();
private:
	static int totalSold;
};
#endif


HD.cpp

#include "HD.h"
int HotDogStand::totalSold = 0;


// ======================
// HotDogStand::HotDogStand
// The default constructor initializes the ID and num sold to zero.
// ======================
HotDogStand::HotDogStand()
{
	numSold = 0;
	ID = 0;
}

// ======================
// HotDogStand::HotDogStand
// This constructor initializes the ID and num sold.
// ======================
HotDogStand::HotDogStand(int newID, int newNumSold)
{
	numSold = newNumSold;
	ID = newID;
}

// ======================
// HotDogStand::GetID
// Returns the ID number of this stand.
// ======================
int HotDogStand::GetID()
{
	return ID;
}

// ======================
// HotDogStand::SetID
// Sets the ID number of this stand.
// ======================
void HotDogStand::SetID(int newID)
{
	ID = newID;
}

// ======================
// HotDogStand::JustSold
// Increments the number of hotdogs this stand
// has sold by one.
// ======================
void HotDogStand::JustSold()
{
	numSold++;	// increment number sold at this stand
	totalSold++;    // increment number sold across all stands
}

// ======================
// HotDogStand::GetNumSold
// Returns the number of hotdogs this stand has sold.
// ======================
int HotDogStand::GetNumSold()
{
	return numSold;
}

// ======================
// HotDogStand::GeTotalSold
// Returns the number of hotdogs sold by all stands
// ======================
int HotDogStand::GetTotalSold()
{
	return totalSold;
}


main.cpp


#include <iostream>
#include "HD.h"

using namespace std;


// ======================
//     main function
// ======================
int main()
{
	 int count;
	 HotDogStand* sList; // HotDogStand sList[10];
	 cout << "Stand count(3개~10개) : ";
	 cin >> count;
	 sList = new HotDogStand[count];
	 for (int i = 0; i < count; i++) {
	  sList[i].SetID(i);
	 }
	 char input;
	 while (true)
	 {
	  cout << "ID : ";
	  cin >> input;
	  if (input == 'q' || input == 'Q')
	   break;
	  int id = input - '0';
	  if(id >= 0 && id < count) // 인덱스 범위 안에 들면
	   sList[id].JustSold();
	 }

	 for (int i = 0; i < count; i++) {
	  cout << "Stand " << sList[i].GetID();
	  cout << " sold " << sList[i].GetNumSold() << endl;
	 }

	 cout << "Total sold = " << HotDogStand::GetTotalSold() << endl;

	 if (sList)
	  delete[] sList;
	 sList = NULL;

  //// Test our code with three hot dog stands
  //HotDogStand s1(1,0),s2(2,0),s3(3,0);
  //
  //// Sold at stand 1, 2
  //s1.JustSold();
  //s2.JustSold();
  //s1.JustSold();

  //cout << "Stand " << s1.GetID() << " sold " << s1.GetNumSold() << endl;
  //cout << "Stand " << s2.GetID() << " sold " << s2.GetNumSold() << endl;
  //cout << "Stand " << s3.GetID() << " sold " << s3.GetNumSold() << endl;
  //cout << "Total sold = " << HotDogStand::GetTotalSold() << endl;
  //cout << "Total sold = " << s1.GetTotalSold() << endl;
  //cout << endl;

  //// Sold some more
  //s3.JustSold();
  //s1.JustSold();

  //cout << "Stand " << s1.GetID() << " sold " << s1.GetNumSold() << endl;
  //cout << "Stand " << s2.GetID() << " sold " << s2.GetNumSold() << endl;
  //cout << "Stand " << s3.GetID() << " sold " << s3.GetNumSold() << endl;
  //cout << "Total sold = " << HotDogStand::GetTotalSold() << endl;
  //cout << "Total sold = " << s1.GetTotalSold() << endl;
  //cout << endl;
  return 0;
}


main.cpp

#include <iostream>
#include "Circle.h"
using namespace std;

int main(void)
{

	int count = 0;
	int num = 0;

	// 사용자에게 circle의 개수를 묻는다
	cout << "Number of Circle: ";
	cin >> count;
	Circle* p = new Circle[count];

	// 사용자에게 각 object의 radius를 묻는다
	for (int i = 0; i < count; i++)
	{
		int rad;
		cout << "Input [" << i << "] Circle radius: ";
		cin >> rad;
		(p + i)->setRadius(rad);
	}
	// circle의 면적을 계산해서 보이고 100~200 사이인 Circle의 개수를 출력
	for (int j = 0; j < count; j++)
	{
		cout << "[" << j << "] Circle area is " << (p + j)->getArea() << endl;
		if (100 <= (p + j)->getArea() && 200 >= (p + j)->getArea())
		{
			num++;
		}
	}
	cout << "Number of Circle area is in scope: " << num << endl;
	delete[] p;
	p = NULL;

	//ShowYourself
	Circle obj1(5);
	obj1.ShowYourself();
	cout << "&obj1: " << &obj1 << endl;

	return 0;
}


Circle.cpp

#include <iostream>
using namespace std;
#include "Circle.h"
int Circle::numObjs = 0; //static member initialization

double Circle::getArea() //member function
{
	return radius * radius * 3.14;
}
double Circle::getRadius()
{
	return radius;
}

void Circle::setRadius(double r)
{
	radius = r;
}
Circle::Circle() //constructor without arg
{
	cout << "constructor without arg" << endl;
	radius = 1;
	numObjs++;
}
Circle::Circle(double r) //constructor with arg
{
	cout << "constructor with arg" << endl;
	radius = r;
	numObjs++;
}
Circle::Circle(const Circle& obj) //copy constructor
{
	cout << "copy constructor" << endl;
	this->radius = obj.radius;
	numObjs++;
}
Circle::~Circle() //deconstructor
{
	cout << "deconstructor" << endl;
	numObjs--;
}
int Circle::getNumObj()
{
	return numObjs;
}

void Circle::ShowYourself()
{
	cout << "radius: " << radius << ", this: " << this << endl;
}


Circle.h

#ifndef Circle_H
#define Circle_H
class Circle {
private:
	double radius; //menber variables
public:
	double getRadius();
	void setRadius(double r);
	double getArea();//member function
	Circle(); //constructor without arg
	Circle(double r); //constructor with arg
	Circle(const Circle& obj); //copy constructor
	~Circle(); //deconstructor
	void ShowYourself();
private:
	static int numObjs; // static variable
public:
	static int getNumObj();
};
#endif



C++ (5월 10일)



DA obj1;
DA obj2(5);
DA obj3(obj2);

obj1 = obj3; 
// obj1 메모리 해지 + obj3 사이즈로 바꿔줌 (5) + 메모리 새로 확보 


obj1 = obj3; // obj3 ==> 매개 variables
obj1.fun(5)

obj1.operator = (obj3);


메모리 새로 확보 : deep copy (copy constructor)


Deep assignment operator overloading

class DA { 
int* arr; int size; 
public: 
DA & operator= (const DA & other) { 
  if (this != &other) {
     delete [] arr; 
  size = other.size;
  arr = new int[size]; 
  for (int i=0; i<size; i++)
    arr[i] = other.arr[i]; 
   } 
   return *this; 
} 
}; 


Point arrS[3]; // point 
arrS[0]; // point 
arrS; // point* 



C++ (5월 23일)


main.cpp

#include <iostream>
#include "Account.h"
using namespace std;
const int ACC_MAX = 10; // 계좌의 최대 개수 : 10 이라는 뜻
void printMenu();
void MakeAccount(Account** C, int size, int& index);
void Deposit(Account** C, int index);
void Withdraw(Account** C, int index);
void Inquire(Account** C, int index);
void cleanup(Account** C, int index);


enum { MAKE = 1, DEPOSIT, WITHDRAW, INQUIRE, EXIT };

int main() {
	
	int size = ACC_MAX;
	
	Account* C[ACC_MAX]; // 정적 개체포인터 배열
	int index = 0;
	int choice;
	while (true) {
		printMenu();
		cout << "선택";
		cin >> choice;
		switch (choice)
		{
		case MAKE:
			MakeAccount(C, index, size);
				break;
		case DEPOSIT:
			Deposit(C, index);
				break;
		case WITHDRAW:
			Withdraw(C, index);
				break;
		case INQUIRE:
			Inquire(C, index);
				break;
		case EXIT:
				cout << "EXIT" << endl;
				cleanup(C, index);
				break;
			default:
				cout << "Wrong Choice" << endl;
				break;
		}
	}

	return 0;
}

void printMenu() {
	cout << "--------MENU--------";
	cout << "1 (계좌 개설) " << endl;
	cout << "2 (입금) " << endl;
	cout << "3 (출금) " << endl;
	cout << "4 (전체조회) " << endl;
	cout << "5 (프로그램 종료) " << endl;

}
// index = 실질적인 계좌의 개수
// size = 계좌의 최대 개수
// Pass By Reference 필수

void MakeAccount(Account** C, int size, int& index) {
	int id, balance;
	char name[NAME_LEN];
	if (index < size) {
		cout << "계좌 개설을 위한 입력 (id 잔액 이름) ";
		cin >> id >> balance >> name;
		C[index] = new Account(id, balance, name); // 인자 있는 생성자 !! 
		index++;
		cout << endl;

	}
	else {
		cout << "최대 계좌 개수에 도달했습니다. " << endl;
	}
}
void Deposit(Account** C, int index) {
	int m, id;
	cout << "계좌 ID : ";
	cin >> id;
	cout << "입금액 : ";
	cin >> m;
	bool found = false;
	int bal;
	for (int i = 0; i < index; i++) {
		if (C[i]->getId() == id) {
		bal = C[i]->InMoney(m);
		cout << "현재 잔고 : " << bal << endl;
		break;
		}
	}
	if (found == false) {
		cout << "존재하지 않는 아이디입니다" << endl;
	}
}
void Withdraw(Account** C, int index) {

}
void Inquire(Account** C, int index) {
	for (int i = 0; i < index; i++) {
		C[i]->ShowAllData();
	}
}

void cleanup(Account** C, int index) {
	for (int i = 0; i < index; i++) {
		delete C[i]; C[i] = NULL; 
	}
}

// 객체 하나를 지울 때는 delete !



C++ (6월 6일)


  • overriding vs overring_with_virtual

Base 에 virtual 선언하면 Derived 에는 굳이 선언 안 해도 됨

Base member → 힘을 살짝 잃는다 라고 표현함

동일한 인터페이스가 필요할 때, 포인터에 의한 Upcasting 을 하면 동일한 인터페이스를 가지고 구현이 가능함


constructor and deconstructor in Inheritance

Base con → Derived con → Derived decon → Base decon


Base *bp = new Derived(); // Upcasted between pointers .
delete bp;

인자 없는 생성자를 불러서 Derived 를 만들고 bp에 주소를 갖게 한 후,

delete bp; 를 한다

~Base(); → ~Base() runs only

즉 virtual ~Base(); and virtual ~Derived(); → dynamic binding

decon도 virtual 을 반드시 붙여줘야 한다 . // dervied , base decon 을 실행하려면 ..


public : 

virtual void Print();

//

AAA b;
BBB d;
b = d;
b.Print();
AAA* bp = new BBB;
bp -> Print();
delete bp;
bp = NULL;


가상함수와 vptr


  • 가상 포인터는 가상함수 테이블의 주소를 가짐
  • 클래스에 가상함수가 존재하면, 컴파일러는 가상함수 테이블 (Vtable) 과 가상 포인터 (vptr) 를 만든다


Size가 내가 생각한 것과 다를 경우

data members 의 Order 에 따라서 Byte padding 이 들어 갈 수도 있고 안 들어 갈 수도 있음 ..


Abstract Class

  • provide general members , interface for polymorphism


Concrete Class

  • to be instantiated (객체)


Employee (cpp, h, main)


Categories:

Updated:

Leave a comment