Type conversion (C++)

1. Introduction

The meaning of type conversion is to change the way the variable is represented by changing the type of a variable to another type.

Two, C++ mandatory type conversion

C-style coercion is not safe.

C++ forced type conversion:

  • Four keywords static_cast, const_cast, reinterpret_cast and dynamic_cast have been added to the C++ language. These four keywords are used for forced type conversion.
  • The new type of forced conversion can provide better control over the forced conversion process, allowing control of various types of forced conversion.
  • The style in C++ is static_cast(content). The other benefit of C++-style casts is that they can clearly indicate what they are doing. As long as the programmer glances at such code, he can immediately know the purpose of a coercion.

Three, specific introduction

1. static_cast: General conversion, used for coercive conversion of data types, forcing one data type to be converted to another data type.

	int a = 98;
	char c = static_cast<char>(a);
	cout << c << endl;// b

Basic data type pointer, object pointer cannot be converted.

	//基础数据类型指针
	int* p = NULL;
	char* sp = static_cast<char*>(p);//无效

	//对象指针
	Building* building = NULL;
	Animal* ani = static_cast<Animal*>(building);//无效



Can convert pointers or references with inheritance

	//父类指针转成子类指针
	Animal* ani = NULL;
	Cat* cat = static_cast<Cat*>(ani);
	//子类指针转成父类指针
	Cat* soncat = NULL;
	Animal* anifather = static_cast<Animal*>(soncat);

	//还有具有继承关系的指针或者引用
	Animal aniobj;
	Animal& aniref = aniobj;
	Cat& cat = static_cast<Cat&>(aniref);

	Cat catobj;
	Cat& catref = catobj;
	Animal& anifather2 = static_cast<Animal&>(catref);	

2. dynamic_cast<type_id> (expression), when converting pointers or references with inheritance relationship, the object type will be checked before conversion, and the conversion
from subtype to base type may fail.

  1. The other three are completed at compile time, dynamic_cast is processed at runtime, and type checking is performed at runtime.

  2. Cannot be used for coercion of built-in basic data types .

    int a = 10;
    char c = dynamic_cast<char>(a);//无效
    
  3. The dynamic_cast conversion returns a pointer or reference to the class if it succeeds, and NULL if the conversion fails.

  4. If you use dynamic_cast for conversion, there must be a virtual function in the base class, otherwise the compilation will not pass.

    B中需要检测有虚函数的原因:类中存在虚函数,就说明它有想要让基类指针或引用指向派生类对象的情况,此时转换才有意义。这是由于运行时类型检查需要运行时类型信息,而这个信息存储在类的虚函数表中,只有定义了虚函数的类才有虚函数表。

  5. In the conversion of classes, the effects of dynamic_cast and static_cast are the same when performing upstream conversion between class levels. When performing downstream conversion, dynamic_cast has the function of type checking, which is safer than static_cast.

    ​ Up-conversion, that is, the sub-class pointer points to the parent-class pointer (generally no problem), the memory is large and small; down-conversion, that is, the parent class pointer is converted to the sub-class pointer, which is not safe. The success of the down conversion is also related to the type to be converted, that is, the actual type of the object pointed to by the pointer to be converted must be the same as the object type after the conversion, otherwise the conversion will fail.

    In C++, the type conversion at compile time may cause errors at runtime, especially when it involves pointer or reference operations of class objects. The Dynamic_cast operator can test type conversions that may cause problems at runtime.

	//非继承关系的指针
	Animal* ani = NULL;
	Building* building = dynamic_cast<Building*>(ani);//报错
	//具有继承关系指针
	Animal* ani = NULL;
	Cat* cat = dynamic_cast<Cat*>(ani);//报错  原因在于 dynamic做类型安全检查

	Cat* cat = NULL;
	Animal* ani = dynamic_cast<Animal*>(cat);

**3, const_cast: **const qualifier is usually used to limit the variable, used to indicate that the value of the variable cannot be modified, and const_cast is used to force the removal of this constant feature that cannot be modified, but it needs special Note that const_cast is not used to remove the constancy of variables, but to remove the constancy of pointers or references to constant objects. The object that removes constancy must be pointers or references.

  1. The constant pointer is forced to be a non-const pointer and still points to the original object;
  2. Constant references are forced to be non-const references and still point to the original object;
  3. Constant objects are forced into non-constant objects.
	//基础数据类型
	int a = 10;
	const int& b = a;	//b = 10;
	int& c = const_cast<int&>(b);
	c = 20;
	cout << "a:" << a << endl;//20
	cout << "b:" << b << endl;//20
	cout << "c:" << c << endl;//20

	const int a = 10;
	const int& pp = a;
	int& cc = const_cast<int&>(pp);
	cc = 100;
	

	//指针   增加或者去除变量的const性
	const int* p = NULL;
	int* p2 = const_cast<int*>(p);

	int* p3 = NULL;
	const int* p4 = const_cast<const int*>(p3);

4、reinterpret_cast 用法:reinterpret_cast<type_id> (expression)

There are three main purposes of reinterpret_cast for forced conversion:

  1. Change the type of pointer or reference,
  2. Convert the pointer or reference into an integer of sufficient length,
  3. Convert an integral type to a pointer or reference type.

The type-id must be a pointer, reference, arithmetic type, function pointer, or member pointer.

It can convert a pointer to an integer, and it can also convert an integer to a pointer (first convert a pointer to an integer, after converting the integer to a pointer of the original type, you can also get the original pointer value).

The forced conversion process when using reinterpret_cast is only a copy of bits, so you need to be especially careful during use!

	//1. 无关的指针类型都可以进行转换
	Building* building = NULL;
	Animal* ani = reinterpret_cast<Animal*>(building);

	//2. 函数指针转换
	FUNC1 func1;
	FUNC2 func2 = reinterpret_cast<FUNC2>(func1);

4. Conclusion

  • You must clearly know the variable to be transformed, what type it was before the transformation, what type it was after the transformation, and what are the consequences after the transformation.
  • In general, it is not recommended to use type conversion to avoid type conversion.

Guess you like

Origin blog.csdn.net/weixin_45341339/article/details/111993677