-
[cpp] explicit, mutable 키워드C++(cpp) 2021. 6. 24. 13:04
Explicit-명시적, implicit-암시적
#include <iostream> #include <string.h> class Exp{ char* _str; public: Exp(char const* str){ _str = new char[strlen(str + 1)]; strcpy(_str, str); }; Exp(int a){ _str = new char[a + 1]; strlcpy(_str, (char const*)"aaaaaaaaaaa", a + 1); }; Exp(char a){ _str = new char[2]; _str[0] = a; _str[1] = '\0'; }; void print(){ std::cout << _str << std::endl; } }; void printString(Exp s) { s.print(); }; int main() { printString("test"); printString('c'); printString(3); }함수 printStirng은 인자로 Exp 객체를 받는데, Exp 객체 대신에 문자열이나 문자나 정수를 넣어도 알아서 Exp의 생성자 중에 하나를 택하여 Exp로 만들어서 넘겨준다. 이것을 암시적(implicit) 변환이라고 함.
암시적으로 변환 되는 것을 원치 않으면 explicit를 붙여주면 된다.
explicit Exp(int a){ _str = new char[a + 1]; strlcpy(_str, (char const*)"aaaaaaaaaaa", a + 1); };Exp 생성자중의 하나에 explicit를 붙여보자. 그리고 컴파일하면 `printString(3);` 코드는 무시하고 실행해주지 않는다.
printString까지는 들어가는데, s.print()를 실행 못하는 듯.
Mutable : 변할 수 있는
const를 붙여놓은 함수들은 해당 함수 안에서 data를 변경하지 않겠다는 표시이다.
그런데 코드를 짜다보면 그런 함수들에서도 데이터를 수정해야하는 순간이 있다고 한다.
[ 예제 ]
#include <iostream> class Mut{ mutable int _a; public: Mut(){ _a = 3; }; void resetInt(int a) const { _a = a; }; void printInt() const { std::cout << _a << std::endl; }; }; int main() { Mut mut; Mut mut2; mut.resetInt(4); mut.printInt(); mut2.resetInt(5); mut2.printInt(); }'C++(cpp)' 카테고리의 다른 글
[cpp] 디폴트 인자 (0) 2021.06.24 [cpp] 연산자 오버로딩 (0) 2021.06.24 [cpp] 소멸자, 복사 생성자 (0) 2021.06.24 [cpp] 지금까지 배운 것 실습 (0) 2021.06.23 [cpp] 함수 오버로딩, 생성자, 디폴트 생성자 (0) 2021.06.21