C++回顾day03---<类型转换>

时间:2023-03-10 03:23:00
C++回顾day03---<类型转换>

一:C++类型转换

(一)static_cast<>() 静态类型转换:基本类型可以转换但是指针类型不允许。可以进行隐式类型转换

double n=1.23
int m=static_case<>(n)

(二)reinterpreter_cast<>() 重新解释类型:同C中的强制类型转换。可以转换指针

char* p = "Hello";
int* pi = reinterpret_cast<int *>(p);

(三)dynamic_cast<>() 多态类型转换:用于实现多态的子类和父类之间的转换

class A
{
public:
int a;
public:
A(int n)
{
this->a = n;
} virtual void say()
{
cout << "A say" << endl;
}
}; class B :public A
{
public:
int b; B(int m, int n) :A(n)
{
this->b = m;
} virtual void say()
{
cout << "B say" << endl;
}
};
void main()
{
A* a = new B(10,5);
B* b = dynamic_cast<B*>(a); //父类和子类必须满足多态要求(含有virtual函数重写)

system("pause");
}

(四)const_cast<>():去除变量的只读属性(前提是变量在内存中可以修改)

void ReadOnly(const char* name)
{
char* tn = const_cast<char*>(name);
tn[] = 'W';
} void main()
{
char name[] = "Hello";
cout << name << endl;
ReadOnly(name);
cout << name << endl;
system("pause");
}

C++回顾day03---<类型转换>

若是不允许修改:

C++回顾day03---<类型转换>