bosthhe1 / cpushpush

0 stars 0 forks source link

类型转换标准 #52

Open bosthhe1 opened 1 year ago

bosthhe1 commented 1 year ago

由于类型转换在很多场景,会造成一些坑,所以c++定义出4种类型的转换,static_cast,reinterpret_cast,const_cast,dynamic_cast。

bosthhe1 commented 1 year ago

static_cast可用于能发生隐士类型转换的,不支持不相管的类型转换,属于静态转换 相关类型可以转换,不相干类型转换报错 image

这里需要注意转换的书写格式

bosthhe1 commented 1 year ago

reinterpret_cast是将一种类型强制类型转换为另外一种不同的类型,这里才有点明白隐士类型转换和强制类型转换的区别,以前虽然都在用,但是并没有太注意这一块 image

bosthhe1 commented 1 year ago

const_cast可以删除常量的const属性,方便赋值 image image 我们看到编译器并没有开tmp,所以就是直接对a赋值

int main()
{
    const int a = 0;
    int* p = const_cast<int*>(&a);
    *p = 1;
    cout << "begin" << endl;
    if (a)
    {
        cout << "hahah" << endl;
    }
    cout << "end" << endl;
        return 0;
}

WNT{EA_6MFX0JC_I9F4{WAJ

我们看到按道理应该会打印"hahah",但是实际上却没有答应出来,这是因为const属性,让编译器r认为这个数不会被修改,所以直接将这个数存在寄存器中,就不用通过内存访问,可以提高效率,但是实际上却改了,但编译器也不知道,这里可以加入volatile关键字,这个关键字不多说了 JQ`78C8 C$VAT(I_L$SDV8

bosthhe1 commented 1 year ago

dynamic_cast是用于将父类对象的指针或引用转换为子类对象的指针或引用,这里的转换只能发生在子类指针被转化为父类指针的时候,被强转回去的用法,且dynameic_cast只能用于存在虚函数的类的转换 向上转换:子类指针或者引用交给父类指针或引用发生切片,编译器自带行为不需要转换 向下转换:子类指针->父类指针->子类指针,需要dynamic_cast进行转换

class A
{
public:
    virtual void func(void)//需要注意dynamic_cast需要存在虚函数才能完成转化
    {
        cout << "A()" << endl;
    }
};
class B :public A
{
public:
    virtual void func(void)
    {
        cout << "B()" << endl;
    }
};

image