ProgrammingLang/c++

[C++ 개발자되기] 21. c++ 키워드 정리

jinkwon.kim 2021. 7. 5. 14:42
728x90
반응형

explicit

explicit 키워드는 Class의 생성자나 복사 생성자에서 자신이 원하지 않은 형변환이 일어나지 않도록 제한하는 키워드

Ex) 형 변환 금지

class Test
{
public:
    explicit Test(int a)
    {
        value = a;
    }
    int value;

};

void PrintA(Test A)
{
    std::cout << A.value << std::endl;
}

int main(int argc, char** argv)
{
    int b = 1;
    Test a(b);
    PrintA(1);
}

위 코드에서 Class Test를 생성자에 explicit을 줌으로써 PrintA의 parameter인 Class Test가 1로 변경된 것을 막았다.

delete

이함수 쓰지 마라는 프로그램의 경고

#include <iostream>
#include <memory>


class Test
{
public:
    explicit Test(int a)
    {
        value = a;
    }
    int value;

    void get() = delete;

};

void PrintA(Test A)
{
    std::cout << A.value << std::endl;
}

int main(int argc, char** argv)
{
    int b = 1;
    Test a(b);
    PrintA(Test(1));
    a.get(); // 이거 에러발생
}

위 코드에서 void get() 함수는 delete로 지워졌기 때문에 사용할 수 없다.

728x90
반응형