# Language & Tools/C++
[C/C++] const 지정자
dream_for
2021. 4. 15. 13:19
명품 C++ 프로그래밍 5장 실습 #11번
main 함수로부터 포인터(문자 배열)를 입력 받아
기존의 값을 변경하는 set함수에서
포인터 매개 변수 값에 const 지정자를 붙이는 것에 의문이 들었다.
void set(const char* title, int price) {
//cout << "set 함수 실행" << endl;
if (this->title) delete[] this->title; // 할당된 메모리가 있다면 반환한후
int len = strlen(title);
this->title = new char[len + 1]; // 새로운 메모리 다시 할당
strcpy(this->title, title);
this->price = price;
}
void show() { cout << title << ' ' << price << "원" << endl; }
};
첫번째 매개 변수 char * title앞에 const 지정자가 붙었다.
#include <iostream>
#include <string>
using namespace std;
class Book {
char* title;
int price;
public:
Book(const char* title, int price) {
//cout << "생성자 실행" << endl;
int len = strlen(title);
this->title = new char[len + 1];
strcpy(this->title, title);
this->price = price;
}
Book(const Book& b) {
//cout << "복사 생성자 실행" << endl;
int len = strlen(b.title);
this->title = new char[len+1];
strcpy(this->title, b.title);
this->price = b.price;
}
~Book() {
if (this->title) {
//cout << "동적 메모리 반환" << endl;
delete[]title;
}
}
void set(const char* title, int price) {
//cout << "set 함수 실행" << endl;
if (this->title) delete[] this->title; // 할당된 메모리가 있다면 반환한후
int len = strlen(title);
this->title = new char[len + 1]; // 새로운 메모리 다시 할당
strcpy(this->title, title);
this->price = price;
}
void show() { cout << title << ' ' << price << "원" << endl; }
};
int main() {
Book cpp("명품C++", 10000);
Book java = cpp; // 복사 생성자 호출
java.set("명품자바", 12000);
cpp.show();
java.show();
}
다음은 const 지정자의 위치에 따라 어떤 차이가 있는지에 대해 설명하는 글이다.
jacking75.github.io/cpp_const_pointer/
C++ - 포인터 변수에서 const 위치에 따른 차이 - jacking75
변수에 const를 사용하는 이유와 사용 방법은 아주 쉽다. 그런데 포인터 타입 변수에 const를 붙였을 때 포인터의 앞이나 뒤 어디에 붙여야 할지 헷갈릴 때가 있다. 포인터에 const를 붙이는 경우 아
jacking75.github.io
728x90
반응형