Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
관리 메뉴

브래의 슬기로운 코딩 생활

C++프로그래밍 11주차 강의 정리 본문

1-2/C++프로그래밍

C++프로그래밍 11주차 강의 정리

김브래 2022. 11. 10. 21:38

오늘은 const와 포인터,

동적 메모리 할당 이라는 것을 배웠다.

 

const는 변수를 상수로 만드는 키워드 이고

 

동적 메모리 할당 이라는건

메모리를 할당할 때 할당할 메모리를

데이터 사이즈에 맞게 자동으로 맞추어 주는 것이다.

const는 이렇게 함수에도 쓰이는데 3번쨰의 경우가 중요하다.

3번째 함수 처럼 쓰면 

함수 블록 내부에 있는 맴버 변수의 값은 변경하지 않는다는 말이댜.

그래서 단순히 맴버 변수의 값을 리턴하는 getter함수는 거의 모두 const를 써도 된다.

 

그리고 만약 멤버 함수를 가지고 있는 함수에 const 키워드를 붙이려면 그 멤버 함수도 const함수 여야 한다.

왜냐하면 그 멤버 함수가 멤버 변수의 값을 변화 시킬수 있기 때문이다.

그래서 일반 멤버 함수에는 접근할 수 없다.

 

const 형을 선언할 때에는

멤버 변수는 앞에 쓰고 멤버 함수는 뒤에 const를 붙인다.

 

const 객체도 선언이 가능한데

const 객체는 그 객체의 초기화된 데이터는 변경할 수 없다.

 

포인터

 

포인터변수는 주소를 저장하는 변수 이다.

포인터 변수를 선언할 때 사용 하는 * 의 용도는 4가지 이다.

주석, 곱하기 연산자,포인터 구두점,포인터 연산자

 

그래서 포인터 변수 앞에 *를 붙이면

포인터 변수의 주소로 가서 값을 가져오라는 뜻이다.

 

그리고 포인터변수에 1을 더하면 char는 1바이트, int형은 4바이트, double형은 8바이트가 증가한다. 

배열의 이름 == 그 배열의 시작 주소를 저장하는 포인터 이다.
그래서 x[i] == *(x+i) 이다. 또 x[1] == 1[x] 이기도 하다.

 

전역변수와 지역변수

 

전역변수는 초기화를 하지 않으면 자동으로 0으로 초기화가 되고

프로그램이 끝날 때까지 값이 유지가 된다.

그리고 전역변수와 지역변수가 이름이 같다면 지역변수가 우선이다.

하지만 지역변수는 함수가 끝나면 사라진다. 

 

동적 메모리 할당

 

동적 메모리를 사용하는 이유

 

프로그램이 끝날 때까지 값을 유지

프로그램을 실행할 때 메모리의 양을 결정

지역 변수가 저장되는 스택은 한정되어 있어 큰 크기는 할당이 어렵다

 

C++에서 동적 메모리 할당

 

메모리를 할당할 떄 new를 사용

할당된 메모리를 헤제할 때 delete를 사용

new는 메모리를 동적으로 할당하고, 할당된 메모리에 대한 주소를 반환하는 연산자

new 배열 / 배열의 첫번째 주소

 

deletwe는 더 이상 필요 없는 메모리를 해제한다

 

 

과제

 

 

#define IN 1 // 컴파일 전에 IN을 찾아서 1로 바꿈

#include <iostream>

int main()

{

const int x = 2; // 변수 x는 항상 1, 변경 불가, 초기값 지정해야

int const y = 3; // 비추, const는 자료형 앞에 씀

const int z{ 4 }; // Uniform initialization, C++11, z{}

constexpr int a = 5; //C++11부터 가능, compile-time constant

//x = 2; //변경 불가

std::cout << IN << x << y << z << a;

return 0;

 

변수를 상수로 만드는 4가지 방법

const int x=1

int const x=1

const int x{1}

constexpr int x=1

 

#include <iostream>

class Dog {

int age; //private 생략함

public:

int getAge() const {

view(); // 오류

return age; // 오류

}

;

void setAge(int a) { age = a; }

void view() const { std::cout << "나는 view"; }

};

 

int main()

{

Dog happy;

happy.setAge(5);

std::cout << happy.getAge();

return 0;

}

함수뒤에 const가 있는 경우 멤버 변수가 변할 수 없고 멤버 함수를 호출한다면 그 함수도 const가 있어야 한다.

 

#include <iostream>

class Dog {

int age;

public:

Dog(int a) { age = a; }

int getAge() const;

void setAge(int a) { age = a; }

void view() const

{

std::cout << "나는 view\n";

}

};

int Dog::getAge() const

{

view();

return (age);

}

int main()

{

const Dog happy(5); //const 객체

//happy.setAge(7); // 오류

std::cout << happy.getAge();

return 0;

}

 

포인터 변수: 주소를 저장하는 변수

*의 용도: 곱하기 연산자, 주석, 포인터 연산자, 포인터 구두점

 

#include <iostream>

using std::cout;

using std::endl;

int main()

{

int x = 10;

int* px = &x;

cout << x << " " << px << " " << *px << endl;

return 0;

}

#include <iostream>

int main(void)

{

int x = 10, y;

int* px; // 선언문, 포인터 px선언

 

px = &x; // 포인터 pxx의 주소 대입

y = *px; // 실행문, px의 주소로 가서 값을 가져옴

std::cout << x << " " << &x << std::endl;

std::cout << sizeof(x) << " " << sizeof(&x) << std::endl;

std::cout << px << " " << &px << " " << *px << std::endl;

std::cout << y << " " << &y;

return 0;

}

포인터 변수에는 그 변수의 주소를 저장

포인터에 1을 더하면(char : 1바이트, int: 4바이트, double : 8바이트)만큼 증가

 

 

 

 

배열의 이름은 그 배열의 시작 주소이다.

 

#include <iostream>

int main(void)

{

int x[5] = { 10,20,30,40,50 };

 

std::cout << x << ":" << *x << x[0] << 0[x] << std::endl;

std::cout << x + 0 << ":" << *(x + 0) << *(0 + x) << x[0] << 0[x] << std::endl;

std::cout << x + 1 << ":" << *(x + 1) << *(1 + x) << x[1] << 1[x] << std::endl;

return 0;

}

 

#include <iostream>

void show1(void);

void show2(void);

int x; //전역 변수

int main(void)

{

std::cout << "main()에서 x:" << x << std::endl;

show1();

std::cout << "show1()호출 후 x:" << x << std::endl;

show2();

std::cout << "show2()호출 후 x:" << x << std::endl;

return 0;

}

void show1(void)

{

std::cout << "show1()에서 x:" << ++x << std::endl;

}

void show2(void)

{

int x = 10; //지역 변수

std::cout << "show2()에서 x:" << x << std::endl; //같은 이름의 전역 변수와 지역 변수가 있을 때는 지역 변수가 우선

}

 

지역변수와 전역변수

 

전역변수는 초기화 하지 않아도 자동으로 0으로 초기화

함수 정의 안에서의 지역변수가 전역변수보다 우선순위가 높지만

함수를 실행하고 나면 지역변수는 사라짐

 

동적 메모리 할당하는 3가지 이유

프로그램이 끝날 때 까지 값을 유지하기 위해

실행할 때 메모리의 양을 결정하기 위해

 

#include <iostream>

int main()

{

int* pi = new int; // 메모리 할당

int x;

 

if (!pi) { // pi==0, 널 포인터인지 확인

std::cout << "메모리할당이 되지 않았습니다.";

return 1; //비정상 종료시 리턴값

}

*pi = 100; //주소의 값으로 100을 할당

x = 10;

std::cout << "동적메모리=" << *pi << ", x=" << x;

 

delete pi; // 메모리 해제

return 0; // 정상 종료시 리턴값

}

 

#include <iostream>

#include <stdlib.h> //exit(1)

int main()

{

int i, n;

int* num;

std::cout << "몇 개의 숫자를 입력하시겠습니까==";

std::cin >> i;

 

num = new int[i];

if (num == NULL) exit(1); //종료

for (n = 0; n < i; n++)

{

std::cout << "숫자를 입력하십시오 : ";

std::cin >> num[n];

}

std::cout << "당신이 입력한 숫자는: ";

for (n = 0; n < i; n++)

std::cout << num[n] << ", ";

delete[] num; //[]을 생략하면?// delete를 생략하면 메모리 누수(Leak)가 발생한다

return 0;

}

#include <iostream>

 

class Dog {

private:

int age;

public:

int getAge();

void setAge(int a);

};

int Dog::getAge()

{

return age;

}

void Dog::setAge(int a)

{

age = a;

}

int main()

{

Dog* dp;

dp = new Dog; // Dog *dp=new Dog

if (!dp) {

std::cout << "메모리할당 불가!";

return 1;

}

 

dp->setAge(5);

std::cout << "메모리에 할당된 값은 "

<< dp->getAge() << "입니다.";

 

delete dp;

return 0;

}

 

과제

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

int main() {

Cat brae(1, 1.3, "");

brae.setAge(3);

brae.setName("김브래");

brae.setW(12.4);

cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

brae.meow();

}

 

동적 메모리를 할당하는 이유와 방법

 

동적 메모리를 할당하는 이유는 프로그램이 끝날때까지 값을 유지하기 위해서와 실행 전에 메모리의 크기를 정하기 위해서 이다.

동적 메모리를 할당하는 방법은 new 자료형을 써서 포인터 변수에 저장하고 프로그램이 끝나기 전에 delete를 하면 된다.

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

 

int main() {

Cat* brae;

brae = new Cat[10];

for (int i = 0; i < 10; i++) // C++에서는 가능

brae[i].setAge(i);

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

std::cout << i << "번째 객체의 나이는 " <<

brae[i].getAge() << " 입니다. " << endl;

//Cat brae(1, 1.3, "");

//brae.setAge(3);

//brae.setName("김브래");

//brae.setW(12.4);

//cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

//brae.meow();

delete[] brae;

}

#include <iostream>

int main()

{

const int x = 2; // 변수 x는 항상 1, 변경 불가, 초기값 지정해야

int const y = 3; // 비추, const는 자료형 앞에 씀

const int z{ 4 }; // Uniform initialization, C++11, z{}

constexpr int a = 5; //C++11부터 가능, compile-time constant

//x = 2; //변경 불가

std::cout << IN << x << y << z << a;

return 0;

 

변수를 상수로 만드는 4가지 방법

const int x=1

int const x=1

const int x{1}

constexpr int x=1

 

#include <iostream>

class Dog {

int age; //private 생략함

public:

int getAge() const {

view(); // 오류

return age; // 오류

}

;

void setAge(int a) { age = a; }

void view() const { std::cout << "나는 view"; }

};

 

int main()

{

Dog happy;

happy.setAge(5);

std::cout << happy.getAge();

return 0;

}

함수뒤에 const가 있는 경우 멤버 변수가 변할 수 없고 멤버 함수를 호출한다면 그 함수도 const가 있어야 한다.

 

#include <iostream>

class Dog {

int age;

public:

Dog(int a) { age = a; }

int getAge() const;

void setAge(int a) { age = a; }

void view() const

{

std::cout << "나는 view\n";

}

};

int Dog::getAge() const

{

view();

return (age);

}

int main()

{

const Dog happy(5); //const 객체

//happy.setAge(7); // 오류

std::cout << happy.getAge();

return 0;

}

 

포인터 변수: 주소를 저장하는 변수

*의 용도: 곱하기 연산자, 주석, 포인터 연산자, 포인터 구두점

 

#include <iostream>

using std::cout;

using std::endl;

int main()

{

int x = 10;

int* px = &x;

cout << x << " " << px << " " << *px << endl;

return 0;

}

#include <iostream>

int main(void)

{

int x = 10, y;

int* px; // 선언문, 포인터 px선언

 

px = &x; // 포인터 pxx의 주소 대입

y = *px; // 실행문, px의 주소로 가서 값을 가져옴

std::cout << x << " " << &x << std::endl;

std::cout << sizeof(x) << " " << sizeof(&x) << std::endl;

std::cout << px << " " << &px << " " << *px << std::endl;

std::cout << y << " " << &y;

return 0;

}

포인터 변수에는 그 변수의 주소를 저장

포인터에 1을 더하면(char : 1바이트, int: 4바이트, double : 8바이트)만큼 증가

 

 

 

 

배열의 이름은 그 배열의 시작 주소이다.

 

#include <iostream>

int main(void)

{

int x[5] = { 10,20,30,40,50 };

 

std::cout << x << ":" << *x << x[0] << 0[x] << std::endl;

std::cout << x + 0 << ":" << *(x + 0) << *(0 + x) << x[0] << 0[x] << std::endl;

std::cout << x + 1 << ":" << *(x + 1) << *(1 + x) << x[1] << 1[x] << std::endl;

return 0;

}

 

#include <iostream>

void show1(void);

void show2(void);

int x; //전역 변수

int main(void)

{

std::cout << "main()에서 x:" << x << std::endl;

show1();

std::cout << "show1()호출 후 x:" << x << std::endl;

show2();

std::cout << "show2()호출 후 x:" << x << std::endl;

return 0;

}

void show1(void)

{

std::cout << "show1()에서 x:" << ++x << std::endl;

}

void show2(void)

{

int x = 10; //지역 변수

std::cout << "show2()에서 x:" << x << std::endl; //같은 이름의 전역 변수와 지역 변수가 있을 때는 지역 변수가 우선

}

 

지역변수와 전역변수

 

전역변수는 초기화 하지 않아도 자동으로 0으로 초기화

함수 정의 안에서의 지역변수가 전역변수보다 우선순위가 높지만

함수를 실행하고 나면 지역변수는 사라짐

 

동적 메모리 할당하는 3가지 이유

프로그램이 끝날 때 까지 값을 유지하기 위해

실행할 때 메모리의 양을 결정하기 위해

 

#include <iostream>

int main()

{

int* pi = new int; // 메모리 할당

int x;

 

if (!pi) { // pi==0, 널 포인터인지 확인

std::cout << "메모리할당이 되지 않았습니다.";

return 1; //비정상 종료시 리턴값

}

*pi = 100; //주소의 값으로 100을 할당

x = 10;

std::cout << "동적메모리=" << *pi << ", x=" << x;

 

delete pi; // 메모리 해제

return 0; // 정상 종료시 리턴값

}

 

#include <iostream>

#include <stdlib.h> //exit(1)

int main()

{

int i, n;

int* num;

std::cout << "몇 개의 숫자를 입력하시겠습니까==";

std::cin >> i;

 

num = new int[i];

if (num == NULL) exit(1); //종료

for (n = 0; n < i; n++)

{

std::cout << "숫자를 입력하십시오 : ";

std::cin >> num[n];

}

std::cout << "당신이 입력한 숫자는: ";

for (n = 0; n < i; n++)

std::cout << num[n] << ", ";

delete[] num; //[]을 생략하면?// delete를 생략하면 메모리 누수(Leak)가 발생한다

return 0;

}

#include <iostream>

 

class Dog {

private:

int age;

public:

int getAge();

void setAge(int a);

};

int Dog::getAge()

{

return age;

}

void Dog::setAge(int a)

{

age = a;

}

int main()

{

Dog* dp;

dp = new Dog; // Dog *dp=new Dog

if (!dp) {

std::cout << "메모리할당 불가!";

return 1;

}

 

dp->setAge(5);

std::cout << "메모리에 할당된 값은 "

<< dp->getAge() << "입니다.";

 

delete dp;

return 0;

}

 

과제

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

int main() {

Cat brae(1, 1.3, "");

brae.setAge(3);

brae.setName("김브래");

brae.setW(12.4);

cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

brae.meow();

}

 

동적 메모리를 할당하는 이유와 방법

 

동적 메모리를 할당하는 이유는 프로그램이 끝날때까지 값을 유지하기 위해서와 실행 전에 메모리의 크기를 정하기 위해서 이다.

동적 메모리를 할당하는 방법은 new 자료형을 써서 포인터 변수에 저장하고 프로그램이 끝나기 전에 delete를 하면 된다.

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

 

int main() {

Cat* brae;

brae = new Cat[10];

for (int i = 0; i < 10; i++) // C++에서는 가능

brae[i].setAge(i);

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

std::cout << i << "번째 객체의 나이는 " <<

brae[i].getAge() << " 입니다. " << endl;

//Cat brae(1, 1.3, "");

//brae.setAge(3);

//brae.setName("김브래");

//brae.setW(12.4);

//cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

//brae.meow();

delete[] brae;

}

#include <iostream>

int main()

{

const int x = 2; // 변수 x는 항상 1, 변경 불가, 초기값 지정해야

int const y = 3; // 비추, const는 자료형 앞에 씀

const int z{ 4 }; // Uniform initialization, C++11, z{}

constexpr int a = 5; //C++11부터 가능, compile-time constant

//x = 2; //변경 불가

std::cout << IN << x << y << z << a;

return 0;

 

변수를 상수로 만드는 4가지 방법

const int x=1

int const x=1

const int x{1}

constexpr int x=1

 

#include <iostream>

class Dog {

int age; //private 생략함

public:

int getAge() const {

view(); // 오류

return age; // 오류

}

;

void setAge(int a) { age = a; }

void view() const { std::cout << "나는 view"; }

};

 

int main()

{

Dog happy;

happy.setAge(5);

std::cout << happy.getAge();

return 0;

}

함수뒤에 const가 있는 경우 멤버 변수가 변할 수 없고 멤버 함수를 호출한다면 그 함수도 const가 있어야 한다.

 

#include <iostream>

class Dog {

int age;

public:

Dog(int a) { age = a; }

int getAge() const;

void setAge(int a) { age = a; }

void view() const

{

std::cout << "나는 view\n";

}

};

int Dog::getAge() const

{

view();

return (age);

}

int main()

{

const Dog happy(5); //const 객체

//happy.setAge(7); // 오류

std::cout << happy.getAge();

return 0;

}

 

포인터 변수: 주소를 저장하는 변수

*의 용도: 곱하기 연산자, 주석, 포인터 연산자, 포인터 구두점

 

#include <iostream>

using std::cout;

using std::endl;

int main()

{

int x = 10;

int* px = &x;

cout << x << " " << px << " " << *px << endl;

return 0;

}

#include <iostream>

int main(void)

{

int x = 10, y;

int* px; // 선언문, 포인터 px선언

 

px = &x; // 포인터 pxx의 주소 대입

y = *px; // 실행문, px의 주소로 가서 값을 가져옴

std::cout << x << " " << &x << std::endl;

std::cout << sizeof(x) << " " << sizeof(&x) << std::endl;

std::cout << px << " " << &px << " " << *px << std::endl;

std::cout << y << " " << &y;

return 0;

}

포인터 변수에는 그 변수의 주소를 저장

포인터에 1을 더하면(char : 1바이트, int: 4바이트, double : 8바이트)만큼 증가

 

 

 

 

배열의 이름은 그 배열의 시작 주소이다.

 

#include <iostream>

int main(void)

{

int x[5] = { 10,20,30,40,50 };

 

std::cout << x << ":" << *x << x[0] << 0[x] << std::endl;

std::cout << x + 0 << ":" << *(x + 0) << *(0 + x) << x[0] << 0[x] << std::endl;

std::cout << x + 1 << ":" << *(x + 1) << *(1 + x) << x[1] << 1[x] << std::endl;

return 0;

}

 

#include <iostream>

void show1(void);

void show2(void);

int x; //전역 변수

int main(void)

{

std::cout << "main()에서 x:" << x << std::endl;

show1();

std::cout << "show1()호출 후 x:" << x << std::endl;

show2();

std::cout << "show2()호출 후 x:" << x << std::endl;

return 0;

}

void show1(void)

{

std::cout << "show1()에서 x:" << ++x << std::endl;

}

void show2(void)

{

int x = 10; //지역 변수

std::cout << "show2()에서 x:" << x << std::endl; //같은 이름의 전역 변수와 지역 변수가 있을 때는 지역 변수가 우선

}

 

지역변수와 전역변수

 

전역변수는 초기화 하지 않아도 자동으로 0으로 초기화

함수 정의 안에서의 지역변수가 전역변수보다 우선순위가 높지만

함수를 실행하고 나면 지역변수는 사라짐

 

동적 메모리 할당하는 3가지 이유

프로그램이 끝날 때 까지 값을 유지하기 위해

실행할 때 메모리의 양을 결정하기 위해

 

#include <iostream>

int main()

{

int* pi = new int; // 메모리 할당

int x;

 

if (!pi) { // pi==0, 널 포인터인지 확인

std::cout << "메모리할당이 되지 않았습니다.";

return 1; //비정상 종료시 리턴값

}

*pi = 100; //주소의 값으로 100을 할당

x = 10;

std::cout << "동적메모리=" << *pi << ", x=" << x;

 

delete pi; // 메모리 해제

return 0; // 정상 종료시 리턴값

}

 

#include <iostream>

#include <stdlib.h> //exit(1)

int main()

{

int i, n;

int* num;

std::cout << "몇 개의 숫자를 입력하시겠습니까==";

std::cin >> i;

 

num = new int[i];

if (num == NULL) exit(1); //종료

for (n = 0; n < i; n++)

{

std::cout << "숫자를 입력하십시오 : ";

std::cin >> num[n];

}

std::cout << "당신이 입력한 숫자는: ";

for (n = 0; n < i; n++)

std::cout << num[n] << ", ";

delete[] num; //[]을 생략하면?// delete를 생략하면 메모리 누수(Leak)가 발생한다

return 0;

}

#include <iostream>

 

class Dog {

private:

int age;

public:

int getAge();

void setAge(int a);

};

int Dog::getAge()

{

return age;

}

void Dog::setAge(int a)

{

age = a;

}

int main()

{

Dog* dp;

dp = new Dog; // Dog *dp=new Dog

if (!dp) {

std::cout << "메모리할당 불가!";

return 1;

}

 

dp->setAge(5);

std::cout << "메모리에 할당된 값은 "

<< dp->getAge() << "입니다.";

 

delete dp;

return 0;

}

 

과제

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

int main() {

Cat brae(1, 1.3, "");

brae.setAge(3);

brae.setName("김브래");

brae.setW(12.4);

cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

brae.meow();

}

 

동적 메모리를 할당하는 이유와 방법

 

동적 메모리를 할당하는 이유는 프로그램이 끝날때까지 값을 유지하기 위해서와 실행 전에 메모리의 크기를 정하기 위해서 이다.

동적 메모리를 할당하는 방법은 new 자료형을 써서 포인터 변수에 저장하고 프로그램이 끝나기 전에 delete를 하면 된다.

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

 

int main() {

Cat* brae;

brae = new Cat[10];

for (int i = 0; i < 10; i++) // C++에서는 가능

brae[i].setAge(i);

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

std::cout << i << "번째 객체의 나이는 " <<

brae[i].getAge() << " 입니다. " << endl;

//Cat brae(1, 1.3, "");

//brae.setAge(3);

//brae.setName("김브래");

//brae.setW(12.4);

//cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

//brae.meow();

delete[] brae;

}

#include <iostream>

int main()

{

const int x = 2; // 변수 x는 항상 1, 변경 불가, 초기값 지정해야

int const y = 3; // 비추, const는 자료형 앞에 씀

const int z{ 4 }; // Uniform initialization, C++11, z{}

constexpr int a = 5; //C++11부터 가능, compile-time constant

//x = 2; //변경 불가

std::cout << IN << x << y << z << a;

return 0;

 

변수를 상수로 만드는 4가지 방법

const int x=1

int const x=1

const int x{1}

constexpr int x=1

 

#include <iostream>

class Dog {

int age; //private 생략함

public:

int getAge() const {

view(); // 오류

return age; // 오류

}

;

void setAge(int a) { age = a; }

void view() const { std::cout << "나는 view"; }

};

 

int main()

{

Dog happy;

happy.setAge(5);

std::cout << happy.getAge();

return 0;

}

함수뒤에 const가 있는 경우 멤버 변수가 변할 수 없고 멤버 함수를 호출한다면 그 함수도 const가 있어야 한다.

 

#include <iostream>

class Dog {

int age;

public:

Dog(int a) { age = a; }

int getAge() const;

void setAge(int a) { age = a; }

void view() const

{

std::cout << "나는 view\n";

}

};

int Dog::getAge() const

{

view();

return (age);

}

int main()

{

const Dog happy(5); //const 객체

//happy.setAge(7); // 오류

std::cout << happy.getAge();

return 0;

}

 

포인터 변수: 주소를 저장하는 변수

*의 용도: 곱하기 연산자, 주석, 포인터 연산자, 포인터 구두점

 

#include <iostream>

using std::cout;

using std::endl;

int main()

{

int x = 10;

int* px = &x;

cout << x << " " << px << " " << *px << endl;

return 0;

}

#include <iostream>

int main(void)

{

int x = 10, y;

int* px; // 선언문, 포인터 px선언

 

px = &x; // 포인터 pxx의 주소 대입

y = *px; // 실행문, px의 주소로 가서 값을 가져옴

std::cout << x << " " << &x << std::endl;

std::cout << sizeof(x) << " " << sizeof(&x) << std::endl;

std::cout << px << " " << &px << " " << *px << std::endl;

std::cout << y << " " << &y;

return 0;

}

포인터 변수에는 그 변수의 주소를 저장

포인터에 1을 더하면(char : 1바이트, int: 4바이트, double : 8바이트)만큼 증가

 

 

 

 

배열의 이름은 그 배열의 시작 주소이다.

 

#include <iostream>

int main(void)

{

int x[5] = { 10,20,30,40,50 };

 

std::cout << x << ":" << *x << x[0] << 0[x] << std::endl;

std::cout << x + 0 << ":" << *(x + 0) << *(0 + x) << x[0] << 0[x] << std::endl;

std::cout << x + 1 << ":" << *(x + 1) << *(1 + x) << x[1] << 1[x] << std::endl;

return 0;

}

 

#include <iostream>

void show1(void);

void show2(void);

int x; //전역 변수

int main(void)

{

std::cout << "main()에서 x:" << x << std::endl;

show1();

std::cout << "show1()호출 후 x:" << x << std::endl;

show2();

std::cout << "show2()호출 후 x:" << x << std::endl;

return 0;

}

void show1(void)

{

std::cout << "show1()에서 x:" << ++x << std::endl;

}

void show2(void)

{

int x = 10; //지역 변수

std::cout << "show2()에서 x:" << x << std::endl; //같은 이름의 전역 변수와 지역 변수가 있을 때는 지역 변수가 우선

}

 

지역변수와 전역변수

 

전역변수는 초기화 하지 않아도 자동으로 0으로 초기화

함수 정의 안에서의 지역변수가 전역변수보다 우선순위가 높지만

함수를 실행하고 나면 지역변수는 사라짐

 

동적 메모리 할당하는 3가지 이유

프로그램이 끝날 때 까지 값을 유지하기 위해

실행할 때 메모리의 양을 결정하기 위해

 

#include <iostream>

int main()

{

int* pi = new int; // 메모리 할당

int x;

 

if (!pi) { // pi==0, 널 포인터인지 확인

std::cout << "메모리할당이 되지 않았습니다.";

return 1; //비정상 종료시 리턴값

}

*pi = 100; //주소의 값으로 100을 할당

x = 10;

std::cout << "동적메모리=" << *pi << ", x=" << x;

 

delete pi; // 메모리 해제

return 0; // 정상 종료시 리턴값

}

 

#include <iostream>

#include <stdlib.h> //exit(1)

int main()

{

int i, n;

int* num;

std::cout << "몇 개의 숫자를 입력하시겠습니까==";

std::cin >> i;

 

num = new int[i];

if (num == NULL) exit(1); //종료

for (n = 0; n < i; n++)

{

std::cout << "숫자를 입력하십시오 : ";

std::cin >> num[n];

}

std::cout << "당신이 입력한 숫자는: ";

for (n = 0; n < i; n++)

std::cout << num[n] << ", ";

delete[] num; //[]을 생략하면?// delete를 생략하면 메모리 누수(Leak)가 발생한다

return 0;

}

#include <iostream>

 

class Dog {

private:

int age;

public:

int getAge();

void setAge(int a);

};

int Dog::getAge()

{

return age;

}

void Dog::setAge(int a)

{

age = a;

}

int main()

{

Dog* dp;

dp = new Dog; // Dog *dp=new Dog

if (!dp) {

std::cout << "메모리할당 불가!";

return 1;

}

 

dp->setAge(5);

std::cout << "메모리에 할당된 값은 "

<< dp->getAge() << "입니다.";

 

delete dp;

return 0;

}

 

과제

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

int main() {

Cat brae(1, 1.3, "");

brae.setAge(3);

brae.setName("김브래");

brae.setW(12.4);

cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

brae.meow();

}

 

동적 메모리를 할당하는 이유와 방법

 

동적 메모리를 할당하는 이유는 프로그램이 끝날때까지 값을 유지하기 위해서와 실행 전에 메모리의 크기를 정하기 위해서 이다.

동적 메모리를 할당하는 방법은 new 자료형을 써서 포인터 변수에 저장하고 프로그램이 끝나기 전에 delete를 하면 된다.

 

#include <iostream>

using namespace std;

class Cat {

private:

int age;

double weight;

string name;

public:

Cat(int age, double weight, string name);

Cat();

~Cat();

int getAge()const;

double getW()const;

string getName()const;

void setAge(int age);

void setW(double weight);

void setName(string Name);

void meow()const;

};

Cat::Cat() {

age = 1;

}

Cat::Cat(int age, double weight, string name) {

this->age = age;

this->weight = weight;

this->name = name;

}

Cat::~Cat() {

cout << "소멸\n";

}

int Cat::getAge() const

{

return age;

}

double Cat::getW() const {

return weight;

}

void Cat::setAge(int age)

{

this->age = age;

}

void Cat::setW(double weight) {

this->weight = weight;

}

void Cat::setName(string Name)

{

this->name = Name;

}

string Cat::getName() const

{

return name;

}

void Cat::meow() const

{

cout << "야옹.\n";

}

 

int main() {

Cat* brae;

brae = new Cat[10];

for (int i = 0; i < 10; i++) // C++에서는 가능

brae[i].setAge(i);

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

std::cout << i << "번째 객체의 나이는 " <<

brae[i].getAge() << " 입니다. " << endl;

//Cat brae(1, 1.3, "");

//brae.setAge(3);

//brae.setName("김브래");

//brae.setW(12.4);

//cout << brae.getAge() << endl << brae.getName() << endl << brae.getW();

//brae.meow();

delete[] brae;

}