도슐랭스타
C++ - const new 본문
strcpy(대상주소, 원본주소);
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using std::cout;
class Cat {
private: //생략가능
int age;
char name[20];
// const char* name; //A
public:
Cat(int age, const char* n) {
this->age = age;
strcpy(name, n); // name=n; //A
cout << name << "고양이 객체가 만들어졌어요.\n";
}
~Cat() { cout << name << "객체 바이\n"; };
int getAge();
const char* getName();
void setAge(int age);
void setName(const char* pName);
void meow();
};
int Cat::getAge() {
return age;
}
void Cat::setAge(int age) {
this->age = age;
}
void Cat::setName(const char* pName) {
strcpy(name, pName);
//strcpy(대상주소, 원본주소);
//strcpy_s(대상주소, 대상의길이, 원본주소);
//name=pName; //A
}
const char* Cat::getName() {
return name;
}
void Cat::meow() {
cout << name << "고양이가 울어요\n";
}
int main() {
Cat nabi(1, "나비"), yaong(1, "야옹"), * pNabi;
cout << nabi.getName() << " 출생 나이는 " << nabi.getAge() << "살이다.\n";
cout << yaong.getName() << " 출생 나이는 " << yaong.getAge() << "살이다.\n";
pNabi = &nabi;
cout << pNabi->getName() << " 출생 나이는 " << pNabi->getAge() << "살이다.\n";
nabi.setName("Nabi");
nabi.setAge(3);
cout << nabi.getName() << " 나이는 " << nabi.getAge() << "살이다.\n";
yaong.meow();
nabi.meow();
return 0;
}
name=pName;
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using std::cout;
class Cat {
private: //생략가능
int age;
std::string name;
// std::string name; //A
public:
Cat(int age, std::string n) {
this->age = age;
name = n; // name=n; //A
cout << name << "고양이 객체가 만들어졌어요.\n";
}
~Cat() { cout << name << "객체 바이\n"; };
int getAge();
std::string getName();
void setAge(int age);
void setName(std::string pName);
void meow();
};
int Cat::getAge() {
return age;
}
void Cat::setAge(int age) {
this->age = age;
}
void Cat::setName(std::string pName) {
name = pName;
//strcpy(대상주소, 원본주소);
//strcpy_s(대상주소, 대상의길이, 원본주소);
//name=pName; //A
}
std::string Cat::getName() {
return name;
}
void Cat::meow() {
cout << name << "고양이가 울어요\n";
}
int main() {
Cat nabi(1, "나비"), yaong(1, "야옹"), * pNabi;
cout << nabi.getName() << " 출생 나이는 " << nabi.getAge() << "살이다.\n";
cout << yaong.getName() << " 출생 나이는 " << yaong.getAge() << "살이다.\n";
pNabi = &nabi;
cout << pNabi->getName() << " 출생 나이는 " << pNabi->getAge() << "살이다.\n";
nabi.setName("Nabi");
nabi.setAge(3);
cout << nabi.getName() << " 나이는 " << nabi.getAge() << "살이다.\n";
yaong.meow();
nabi.meow();
return 0;
}
#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 = 4; //변경 불가
//y = 5; //변경 불가
//z = 10; //변경 불가
std::cout << IN << x << y << z << a;
return 0;
}
const 키워드를 사용한 변수는 초기값에서 다른 값으로 바꿀 수 없다.
const를 반드시 사용해야하는 것은 아니다. 하지만 코드를 보는 사람들이 이해하기 쉽기 때문에 사용하면 좋다.
get() 함수들은 사용하는 것이 좋다.
오류 수정하기
#include <iostream>
class Dog {
int age; //private 생략함
public:
int getAge() const;
void setAge(int a) { age = a; }
void view() { std::cout << "나는 view"; }
};
int Dog::getAge() const
{
view(); // 오류 ①
return (++age); // 오류 ②
}
int main()
{
Dog happy;
happy.setAge(5);
std::cout << happy.getAge();
return 0;
}
오류1
const 함수는 const 함수만 호출할 수 있다. void view() -> void view() const
오류2
const 함수는 멤버 변수를 변경하지 못한다. ++age-> age
수정본
#include <iostream>
class Dog {
int age; //private 생략함
public:
int getAge() const;
void setAge(int a) { age = a; }
void view() const
{
std::cout << "나는 view";
}
};
int Dog::getAge() const
{
view(); // 오류 ①
return (age); // 오류 ②
}
int main()
{
Dog happy;
happy.setAge(5);
std::cout << happy.getAge();
return 0;
}
+
#include <iostream>
class Dog {
int age; //private 생략함
public:
int getAge() const;
void setAge(int a) { age = a; }
void view()
{
age++;
std::cout << "나는 view";
}
};
int Dog::getAge() const
{
view(); // 오류
return (age);
}
int main()
{
Dog happy;
happy.setAge(5);
std::cout << happy.getAge();
return 0;
}
const 함수에서 멤버 변수를 변경한 것은 아니지만 const 함수 안에서 호출한 함수가 멤버 변수를 변경했다.
이런 경우를 막기 위해 const 함수에서는 const 함수만 호출할 수 있다.
지역 변수는 stack에 할당을 한다. 하지만 너무 큰 메모리를 할당하여 문제가 생긴다. 이런 큰 메모리는 동적 메모리인 heap에 할당한다.
★
1. 지역 변수를 전역 변수 처럼 프로그램이 끝날 때까지 값을 유지하고 싶은 경우.
2. 프로그램을 작성할 때 필요한 메모리 공간의 크기를 모르는 상태로 프로그램을 실행(메모리 양을 결정)할 경우.
정적 메모리 할당과 동적 메모리 할당
#include <iostream>
int main()
{
int* pi = new int; // 동적 메모리 할당, heap
int x; //정적 메모리할당, stack
if (!pi) { // pi==0, 널 포인터인지 확인
std::cout << "메모리할당이 되지 않았습니다.";
return 1; //비정상 종료시 리턴값
}
*pi = 100; //주소의 값으로 100을 할당
x = 10;
std::cout << "동적메모리=" << *pi << ", x=" << x;
delete pi; // 메모리 해제
return 0; // 정상 종료시 리턴값
}
new 연산자를 사용하면 동적 메모리에 할당할 수 있다. ' 단,포인터를 사용해야한다! '
이렇게 heap과 stack에 각각 메모리가 할당된다.
delete로 할당을 해제해준다.
만약 동적 메모리 할당을 해제해주지 않으면 프로그램이 끝나도 계속 메모리를 할당한 상태가 된다.
그 메모리를 할당한 부분은 앞으로 사용할 수 없게 된다.
기본 자료형을 동적 메모리 할당할 때는 new 자료형으로 할당할 수 있고,
배열을 동적 메모리 할당할 때는 new 자료형[] 으로 할당할 수 있다.
배열을 해제할 때는 "[]"을 꼭 써줘야한다!
#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; //[]을 생략하면?
return 0;
}
★배열의 이름은 그 배열의 시작 주소이다!
int x[3]={1,2,3}
라면 x[0]=1, x[1]=2, x[2]=3이고 x는 배열의 시작 주소이므로 x=1, x+1=2, x+2=3이다.
배열 객체 동적 할당
#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[10]; // 객체배열 할당
// Dog *dp=new Dog[10];
if (!dp) {
std::cout << "메모리할당이 되지 않았습니다.";
return 1;
}
for (int i = 0; i < 10; i++) // C++에서는 가능
dp[i].setAge(i);
for (int i = 0; i < 10; i++)
std::cout << i << "번째 객체의 나이는 " <<
dp[i].getAge() << " 입니다. " << std::endl;
delete[]dp;
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using std::cout;
class Cat {
private: //생략가능
int age;
std::string name;
public:
Cat(int age, std::string n) {
this->age = age;
name = n;
cout << name << "고양이 객체가 만들어졌어요.\n";
}
~Cat() { cout << name << "객체 바이\n"; };
int getAge() const;
std::string getName() const;
void setAge(int age);
void setName(std::string pName);
void meow() const;
};
int Cat::getAge() const {
return age;
}
void Cat::setAge(int age) {
this->age = age;
}
void Cat::setName(std::string pName) {
name = pName;
}
std::string Cat::getName() const {
return name;
}
void Cat::meow() const {
cout << name << "고양이가 울어요\n";
}
int main() {
Cat nabi(1, "나비"), yaong(1, "야옹"), * pNabi;
cout << nabi.getName() << " 출생 나이는 " << nabi.getAge() << "살이다.\n";
cout << yaong.getName() << " 출생 나이는 " << yaong.getAge() << "살이다.\n";
pNabi = &nabi;
cout << pNabi->getName() << " 출생 나이는 " << pNabi->getAge() << "살이다.\n";
nabi.setName("Nabi");
nabi.setAge(3);
cout << nabi.getName() << " 나이는 " << nabi.getAge() << "살이다.\n";
yaong.meow();
nabi.meow();
return 0;
}
'C++' 카테고리의 다른 글
C++ - Default Parameter (0) | 2023.11.15 |
---|---|
C++ - 함수중첩(Function Overloading) (0) | 2023.11.15 |
C++ - 객체와 멤버 생성자 소멸자 this (1) | 2023.11.01 |
C++-구조체와 클래스 (0) | 2023.10.18 |
C++ 맛보기와 C복습(4)-구조체, 객체지향 프로그래밍 (0) | 2023.10.11 |