类型转换有 c 风格的,当然还有 c++风格的。c 风格的转换的格式很简单(TYPE
EXPRESSION),但是 c 风格的类型转换有不少的缺点,有的时候用 c 风格的转换是不合适的,
因为它可以在任意类型之间转换,比如你可以把一个指向 const 对象的指针转换成指向非
const 对象的指针,把一个指向基类对象的指针转换成指向一个派生类对象的指针,这两种转
换之间的差别是巨大的,但是传统的 c 语言风格的类型转换没有区分这些。还有一个缺点就
是,c 风格的转换不容易查找,他由一个括号加上一个标识符组成,而这样的东西在 c++程
序里一大堆。所以 c++为了克服这些缺点,引进了 4 新的类型转换操作符。
.1.静态类型转换:
语法格式:
static_cast<目标类型> (标识符)
转化规则:
在一个方向上可以作隐式转换,在另外一个方向上就可以作静态转换。
int a = 10;
int b = 3;
cout<<static_cast<float>(a)/b<<endl; //float = int int = float
return 0;
int *p; void *q;
p = static_cast<int*>(q);
char *p = static_cast<char*>(malloc(100));
.2.重解释类型转换:
语法格式:
reinterpret_cast<目标类型> (标识符)
转化规则
“通常为操作数的位模式提供较低层的重新解释”也就是说将数据以二进制存在形式
的重新解释,在双方向上都不可以隐式类型转换的,则需要重解释类型转换。
float a = 5.6; int b = 5; b = static_cast<int>(a); a = static_cast<float>(b); void *p;int *q; p = q; //q = p ;这样就不可以 q = static_cast<int*>(p); int x = 10; int y = 3; float z = static_cast<float>(x)/y; cout<<z<<endl; //char * pc = malloc(100);编译通不过 char *pc = static_cast<char *>(malloc(100)); return 0;
.3.(脱)常类型转换:
语法格式:
const_cast<目标类型> (标识符) //目标类类型只能是指针或引用。
语法规则
用来移除对象的常量性(cast away the constness)使用 const_cast 去除 const 限定的
目的不是为了修改它的内容,使用 const_cast 去除 const 限定,通常是为了函数能够接受
这个实际参数。
应用场景 1:
#include <iostream>
using namespace std;
void func(int & ref) //别人己经写好的程序或类库 { cout<<ref<<endl; } int main(void) { const int m = 4444; func(const_cast<int&>(m)); return 0; }
//脱掉 const 后的引用或指针可以改吗? int main() { const int x = 200; int & a =const_cast<int&>(x); // int &a = x; a = 300; cout<<a<<x<<endl; cout<<&a<<"---"<<&x<<endl; int *p =const_cast<int*>(&x); // int *p = &x; *p = 400; cout<<a<<*p<<endl; cout<<p<<"---"<<&x<<endl; struct A { int data; }; const A xx = {1111}; A &a1 = const_cast< A&>(xx); a1.data = 222; cout<<a1.data<<xx.data<<endl; A *p1 = const_cast<A*>(&xx); p1->data = 333; cout<<p1->data<<xx.data<<endl; return 0; }
结论:
可以改变 const 自定义类的成员变量,但是对于内置数据类型,却表现未定义行为.
Depending on the type of the referenced object, a write operation throu
gh the resulting pointer, reference, or pointer to data member might pr
oduce undefined behavio
const 常变量(补充):
C++中 const 定义的变量称为常变量。变量的形式,常量的作用,用作常量,常用于
取代#define 宏常量。
#define N 200 int main() { const int a = 200; int b = 300; int c = a +b; //int c = N + b; cout<<c<<endl; return 0; }
原文链接: https://www.cnblogs.com/yygsj/p/5693292.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/237449
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!