【C++】学习笔记草稿版系列6(强制类型转换)

static_cast
// dynamic_cast
reinterpret_cast
const_cast

static_cast:对于隐式类型可以转化的,即可以使用此类型。

float a = 5.6;
int b = 5;

b = static_cast<int>(a);
a = static_cast<float>(b); //C++ 不要随意发生强转

void *p; int *q;

p = q; // void * 可以接受任何类型的指针
// q = p; //[ERROR]

q = static_cast<int*>(p);

int x = 10;
int y = 3;

float z = static_cast<float>(x)/y;

char *pc = static_cast<char*>malloc(100);

reinterpret_cast:双方隐式转换都通不过的时候使用

char *p; int *q;

p = reinterpret_cast<char*>(q);
int a[5] = {1, 2, 3, 4, 5};
int *p = reinterpret_cast<int*>(reinterpret_cast<int>(a)+1);

const_cast:脱常,只能引用于指针和引用

 //const 修饰的东西一定不能改

void func(const int & v)// const 对引用的拓展,引用只能够传递变量,而不能传递常量
{
    //不能修改v内的内容;
}

int main()
{
    const int a = 19;
    func(a + 10);
}
void func2(int & v)
{

}

int main()
{
    const int a = 19;
    func2(a); //[ERROR] const int不能传递给一个int类型的变量
}
void func2(int & v)
{

}

int main()
{
    const int a = 19;
    func2(const_cast<int&>(a)); //[ERROR] const int不能传递给一个int类型的变量

    int & ra = const_cast<int&>(a);

    ra = 200;
    cout<<"a = "<<a<<endl;
    cout<<"ra = "<<ra<<endl; //ra的值修改了,但是a的值没有修改
    // 两者的地址一样

    int * pi = const_cast<int*>(&a);
    *pi = 200;
    cout<<"a = "<<a<<endl;
    cout<<"*pi = "<<*pi<<endl; // *pi的值修改了,但是a的值没有修改
    // 两者的地址一样
}
struct A
{
    int data;
};

const A ad = {10};

A * pA = const_cast<A*>(&ad);
pA->data = 200;

cout<<pA->data<<endl; // 输出200

上面的这些代码虽然是看似可以修改const变量引用或指针的值,但是:
妄图对const_cast指针、引用等的修改行为都是未定义的。
换句话说就是,可以改变const自定义类的成员变量,但是对于内置数据类型,却表现未定义行为。
Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.

宏在预处理的时候发生了替换
const在编译的阶段发生了替换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值