cpp拾遗——类型转换

1. c和c++的类型转换

c只有编译时类型转换,包括隐式类型转换和显示类型转换。
cpp有编译时类型转换,和运行时类型转换,和const类型转换,
static_cast 编译时类型转换,效果相当于c的隐式转换
reinterpret_cast 编译时类型转换,效果相当于c的显示类型转换
dynamic_cast 运行时类型转换,父子类之间多态转换
const_cast const类型转换

格式:
type b = static_cast(a);

2. static_cast reinterpret_cast

        int a, *pi;
        char c;

        c = static_cast<char>(a);
        pi = reinterpret_cast<int *>(a);

3. dynamic_cast

多态间转换,如果不能转换,则返回NULL,可用于判断父类指针指向的是哪个子类。

class animal_t {
        public:
                virtual void walk() = 0;
};

class dog_t : public animal_t {
        public:
                void walk() {
                        cout << "dog walk" << endl;
                }
                void house_keeping() {
                        cout << "wang wang" << endl;
                }
};

class cat_t : public animal_t {
        public:
                void walk() {
                        cout << "cat walk" << endl;
                }
                void sell_cute() {
                        cout << "cute cute" << endl;
                }
};

void test(animal_t *a)
{
        a->walk();

        cat_t *cat = dynamic_cast<cat_t *>(a);
        if (cat != NULL) {
                cat->sell_cute();
        }
        dog_t *dog = dynamic_cast<dog_t *>(a);
        if (dog != NULL) {
                dog->house_keeping();
        }
}

int main()
{
        cat_t cat;
        test(&cat);
        dog_t dog;
        test(&dog);

        return 0;
}

4. const_cast

常用于去除const只读属性,但程序员需要保证内存可写。

        const char *str = "aaaaa";
        const char str2[] = "aaaaa";

        char *p;

        p = const_cast<char *>(str);
        p[0] = 1; // 错误
        p = const_cast<char *>(str2);
        p[0] = 1;

posted on 2022-06-06 09:52  开心种树  阅读(90)  评论(0编辑  收藏  举报