logo

C++의 static_cast

Cast 연산자는 단항 연산자 이는 하나의 데이터 유형을 다른 데이터 유형으로 변환하도록 강제합니다.

C++에서는 4가지 유형의 캐스팅을 지원합니다.



  1. 정적 캐스트
  2. 다이나믹 캐스트
  3. Const Cast
  4. 캐스트를 재해석하다

이 기사에서는 static_cast에 대해 자세히 논의하는 데 중점을 둡니다.

정적 캐스트

이것은 사용할 수 있는 가장 간단한 유형의 캐스트입니다. 이것은 컴파일 타임 캐스트 . 이는 유형 간 암시적 변환(예: int에서 float로, 포인터에서 void*로)과 같은 작업을 수행하며 명시적 변환 함수를 호출할 수도 있습니다.

자바 8

static_cast 구문

 static_cast < dest_type>(출처);>

static_cast의 반환 값은 다음과 같습니다. 대상_유형.



static_cast의 예

다음은 static_cast를 구현하는 C++ 프로그램입니다.

C++






// C++ Program to demonstrate> // static_cast> #include> using> namespace> std;> // Driver code> int> main()> {> >float> f = 3.5;> >// Implicit type case> >// float to int> >int> a = f;> >cout <<>'The Value of a: '> << a;> >// using static_cast for float to int> >int> b =>static_cast><>int>>(에프);> >cout <<>' The Value of b: '> << b;> }>

>

>

산출

The Value of a: 3 The Value of b: 3>

다양한 시나리오에 대한 static_cast 동작

1. 기본 데이터 유형 포인터에 대한 static_cast:

이제 위의 코드를 몇 가지 변경해 보겠습니다.

C++




// C++ Program to demonstrate> // static_cast char* to int*> #include> using> namespace> std;> // Driver code> int> main()> {> >int> a = 10;> >char> c =>'a'>;> > >// Pass at compile time,> >// may fail at run time> >int>* q = (>int>*)&c;> >int>* p =>static_cast><>int>*>(&c);> >return> 0;> }>

>

>

산출

error: invalid 'static_cast' from type 'int*' to type 'char*'>

설명: 즉, 특정 객체 포인터를 다른 객체 포인터로 어떻게든 타입캐스트할 수 있다고 생각하지만 그것이 불법이라면 static_cast는 이를 허용하지 않는다는 것을 의미합니다.

2. 사용자 정의 변환 연산자를 사용하여 객체 변환

static_cast는 정의된 클래스의 변환 연산자를 호출할 수 있습니다. 객체를 클래스로 변환하거나 클래스에서 변환하는 또 다른 예를 들어보겠습니다.

예:

C++




// C++ Program to cast> // class object to string> // object> #include> #include> using> namespace> std;> // new class> class> integer {> >int> x;> public>:> >// constructor> >integer(>int> x_in = 0)> >: x{ x_in }> >{> >cout <<>'Constructor Called'> << endl;> >}> >// user defined conversion operator to string type> >operator string()> >{> >cout <<>'Conversion Operator Called'> << endl;> >return> to_string(x);> >}> };> // Driver code> int> main()> {> >integer obj(3);> >string str = obj;> >obj = 20;> >// using static_cast for typecasting> >string str2 =>static_cast>(obj);> >obj =>static_cast>(30);> >return> 0;> }>

자바 휘발성 키워드
>

>

산출

Constructor Called Conversion Operator Called Constructor Called Conversion Operator Called Constructor Called>

설명: 위의 출력을 한 줄씩 이해해 보겠습니다.

  1. 언제 객체 생성된 다음 생성자가 호출됩니다. 이 경우에는 변환 생성자이기도 합니다(C++14 규칙의 경우 약간 변경됨).
  2. 생성할 때 str 밖으로 객체 , 변환 연산자를 정의한 대로 컴파일러는 오류를 발생시키지 않습니다.
  3. 만들 때 객체 = 20 , 실제로 변환 생성자를 호출하고 있습니다.
  4. 만들 때 str2 밖으로 static_cast , 문자열과 매우 유사합니다. str = obj ; 그러나 엄격한 유형 검사가 필요합니다.
  5. 당신이 쓸 때 obj = static_cast (30) , 30을 정수 static_cast를 사용합니다.

3. C++ 상속을 위한 static_cast

static_cast는 상속의 경우 업캐스팅과 다운캐스팅을 모두 제공할 수 있습니다. 다음 예에서는 업캐스팅의 경우 static_cast 사용을 보여줍니다.

예:

C++


하둡 튜토리얼



// C++ Program to demonstrate> // static_cast in inheritance> #include> using> namespace> std;> class> Base> {};> class> Derived :>public> Base> {};> // Driver code> int> main()> {> >Derived d1;> > >// Implicit cast allowed> >Base* b1 = (Base*)(&d1);> > >// upcasting using static_cast> >Base* b2 =>static_cast>(&d1);> >return> 0;> }>

>

>

설명: 위의 코드는 오류 없이 컴파일됩니다.

  1. 우리는 d1의 주소를 가져와 명시적으로 Base에 캐스팅하고 b1에 저장했습니다.
  2. 우리는 d1의 주소를 가져와 static_cast를 사용하여 이를 Base로 캐스팅하고 b2에 저장했습니다.

위의 예에서는 기본 클래스를 공개로 상속했습니다. 비공개로 상속하면 어떻게 되나요? 아래 예에서는 다음을 보여줍니다.

예:

C++




// C++ program to demonstrate> // static_cast in case of> // private inheritance> #include> using> namespace> std;> class> Base> {};> class> Derived:>private> Base> {> >// Inherited private/protected> >// not public> };> // Driver code> int> main()> {> >Derived d1;> > >// Implicit type cast allowed> >Base* b1 = (Base*)(&d1);> > >// static_cast not allowed> >Base* b2 =>static_cast>(&d1);> >return> 0;> }>

>

>

컴파일 시간 오류:

JPA 대 최대 절전 모드
[Error] 'Base' is an inaccessible base of 'Derived'>

설명: 위의 코드는 컴파일하지 않음 당신이 그것을 상속받더라도 보호됨 .

따라서 상속 시 static_cast를 사용하려면 기본 클래스가 가상이 아니고 모호하지 않고 액세스 가능해야 합니다.

4. 공허 포인터 'to and from' 캐스트에 대한 static_cast

static_cast 연산자를 사용하면 모든 포인터 유형에서 void 포인터로 또는 그 반대로 캐스팅할 수 있습니다.

예:

C++




// C++ program to demonstrate> // static_cast to cast 'to and> // from' the void pointer> #include> using> namespace> std;> // Driver code> int> main()> {> >int> i = 10;> >void>* v =>static_cast><>void>*>(&i);> >int>* ip =>static_cast><>int>*>(v);> >cout << *ip;> >return> 0;> }>

>

>

산출

10>