목록C++ (52)
Minwoo Dev.
C++을 공부하다 보면 C언어에서부터 사용하던 malloc과 new가 헷갈릴 수 있다.new와 malloc의 차이점에 대해서 작성해보았다. mallocC언어에서 동적 할당을 사용할 때 사용하였다.malloc은 지정된 바이트 수 만큼 메모리를 할당한다.malloc은 초기화를 진행하지 않고 할당만을 수행한다.malloc은 "함수"이다.int* ptr = (int*)malloc(sizeof(int)); // 단일 정수형 변수 할당*ptr = 5;free(ptr); // 메모리 해제int* arr = (int*)malloc(10 * sizeof(int)); // 정수형 배열 할당free(arr); // ..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/cxJtWd/btsHDf79k2m/OD4CfZ7Vak7btk2yA6699k/img.png)
string문자열을 저장하기 위해서 char형 배열을 사용해야 했던 C언어와는 달리, C++에서는 문자열을 다룰 수 있는 string이 존재한다.변수형처럼 사용하지만, 실제로 string은 클래스(class)이다.#include using namespace std;int main(void){ string s = "안녕하세요."; cout 실행 결과 char* C언어에서 많이 사용되는 문자열 표현 방식.문자 하나를 저장할 수 있는 char을 여러 개 연결하여 배열처럼 사용한다.포인터 값이기 때문에 변수 안에는 문자열의 시작 주소가 담겨있다.#include using namespace std;int main(void){ char *s = "안녕하세요."; cout 실행 결과 v..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/M3Ni2/btsHvrBY35e/cebuYbwWZfJLfOXCNfFs0K/img.png)
문제 1예제 StablePointPtrArray.cpp의 65, 66행을 다음과 같이 구성할 수 있도록 Point 클래스를 대상으로 연산자 오버로딩을 진행해보자for (int i = 0; i 물론, 실행결과에는 변함이 없도록 연산자를 오버로딩 해야한다. 정답#include #include using namespace std;class Point{private: int xpos, ypos;public: Point(int x = 0, int y = 0) : xpos(x), ypos(y) {} friend ostream &operatorxpos ypos = arrlen) { cout = arrlen) { cout 결과 문..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/PI2Cz/btsHrObDECX/hEvnPr13ReN6j0xX7yke1k/img.png)
문제 1Chapter 07에서는 예제 HASComposite.cpp를 통해서 다음의 두 클래스를 정의하였다.(완전한 클래스의 정의는 예제를 참고하자.) class Gun{ ...}class Police { private: int handcuffs; Gun * pistol; public: .... } 이에 Police 클래스를 대상으로 깊은 복사가 이뤄지도록 대입 연산자와 복사 생성자를 동시에 정의하고 이의 확인을 위한 main 함수도 적절히 정의해보자. 정답#include using namespace std;class Gun{private: int bullet;public: Gun(int bnum) : bullet(bnum) {} void Shot() ..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/LgA3I/btsHlF8RtQK/SdRu5h7kalpFq88dlkNmC0/img.png)
예제 PointConsoleOutput.cpp 에서 정의한 Point 클래스를 대상으로 아래의 main 함수가 보이는대로 데이터의 입력이 가능하도록, 그리고 실행의 예에서 보이는 대로 출력이 이루어지도록 >> 연산자를 오버로딩 하자. PointConsoleOutput.cpp#include using namespace std;class Point{private: int xpos, ypos;public: Point(int x = 0, int y = 0) : xpos(x), ypos(y) {} void ShowPosition() const { cout [main 함수]int main(void){ Point pos1; cout > pos1; cout > p..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/cygoqO/btsHnKAH8w0/FhAwYfOJVVZRREBgLKtawk/img.png)
문제 1 : 멤버함수의 형태로 오버로딩부호 연산자로서 - 는 단항 연산자이다. 이 연산자는 피연산자의 부호를 반전시킨 결과를 반환한다.예를 들어서 다음 문장이 실행되면,int num2 = -num1; num2에는 num1과 절대값은 같지만 부호가 다른 값이 저장된다. 물론 num1의 값에는 영향을 미치지 않는다. 이와 유사하게 Point 클래스를 대상으로 - 연산자를 오버로딩해보자.다음의 문장이 실행되면,Point pos2 = -pos1; pos2의 멤버변수는 pos1의 멤버변수 값과 다른 부호의 값으로 초기화되도록 오버로딩해보자. 정답 소스코드#include using namespace std;class Point{private: int xpos, ypos;public: Point(int ..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/bEAyb9/btsHmyuxE5P/ks201ENiE5a5nUQmeXy0c1/img.png)
문제 1Point 클래스에 대해서 다음 조건을 만족하는 형태로 - 연산자를 오버로딩 해보자.전역함수 기반으로 오버로딩멤버 별 - 연산의 결과를 담은 Point 객체 반환 정답소스 코드#include using namespace std;class Point{private: int xpos, ypos;public: Point(int x = 0, int y = 0) : xpos(x), ypos(y) {} void ShowPosition() const { cout 실행 결과 문제 2Point 클래스에 대해서 다음 조건을 만족하는 형태로 += 연산자와 -= 연산자를 오버로딩 해보자.멤버함수 기반으로 오버로딩연산 'pos1 += pos2'의 결과로 pos1의 멤버변수 값이 ..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/l4O8b/btsHa1P0ybs/o9bZJk8Sbdd093NhigXGS0/img.png)
예제 Employeemanager4.cpp를 확장하여 다음 특성에 해당하는 ForeginSalesWorker 클래스를 추가로 정의해보자. Employeemanager4.cpp#include #include using namespace std;class Employee{private: char name[50];public: Employee(char *name) { strcpy(this->name, name); } void ShowYourName() const { cout ShowSalaryInfo(); } void ShowTotalSalary() const { int sum = 0; for (int i = ..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/N0nIb/btsGBiTK5JB/jXjLlV7ot0ykWU7wpwkot0/img.png)
문제 1 정사각형을 의미하는 Square 클래스와 직사각형을 의미하는 Rectangle 클래스를 정의하고자 한다. 그런데 정사각형은 직사각형의 일종이므로, 다음의 형태로 클래스의 상속관계를 구성하고자 한다. class Rectangle{ .... }; class Square : public Rectangle{ .... }; 이에 다음 main 함수와 함께 실행이 가능하도록 위의 클래스를 완성해보자. 참고로 상속을 한다고 해서 유도 클래스에 무엇인가를 많이 담아야 한다는 생각을 버리자. [main 함수] int main(void) { Rectangle rec(4,3); rec.ShowAreaInfo(); Square sqr(7); sqr.ShowAreaInfo(); return 0; } 실행의 예 면적 :..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/qNGoa/btsGCpdsWrQ/iiM2prMNBuFRwZENZ7rbDK/img.png)
문제 1 앞서 상속관계에 놓여있는 클래스의 생성자 정의 및 호출 방식에 대해 설명하였다. 이 내용을 바탕으로 다음 클래스에 적절한 생성자를 삽입해보자. 그리고 이의 확인을 위한 main 함수를 적절히 정의해 보자. class Car { private: int gasolineGauge; public: int GetGasGauge() { return gasolineGauge; } }; class HybridCar : public Car { private: int electricGauge; public: int GetElecGauge() { return electricGauge; } }; class HybridWaterCar : public HybridCar { private: int waterGauge; p..