C++ 检查变量类型

python中有instance判断类型,能够方便对变量类型作出判断。c++中也能实现类是功能。

检查标准变量类型

示例

#include <iostream>
#include <typeinfo>

int main() {
    int num = 42;
    const std::type_info& type = typeid(num);
    
    std::cout << "Variable type: " << type.name() << std::endl;
    
    if (type == typeid(int)) {
        std::cout << "Variable is of type int." << std::endl;
    }
    else if (type == typeid(float)) {
        std::cout << "Variable is of type float." << std::endl;
    }
    // 添加其他类型的检查...

    return 0;
}

在这个示例中,我们定义了一个整数变量 num。然后,使用typeid运算符将变量的类型存储在std::type_info对象 type 中。通过type.name()方法可以获取类型的名称并输出到控制台。

接下来,我们可以使用type和typeid来比较不同类型,并执行相应的操作。在示例中,我们检查num的类型是否等于int和float,并输出相应的消息。

需要注意的是,typeid运算符返回的类型信息是在编译时确定的,所以它对于运行时的多态类型可能不适用。此外,类型名称的具体输出可能因编译器而异。如果需要在运行时进行多态类型的检查,可以使用dynamic_cast和基类的指针/引用进行类型转换和检查

检查自定义的类型

#include <iostream>
#include <typeinfo>

// 自定义结构体
struct MyStruct {
    int value;
};

// 自定义类
class MyClass {
    int value;
};

int main() {
    MyStruct structVar;
    MyClass classVar;

    const std::type_info& structType = typeid(structVar);
    const std::type_info& classType = typeid(classVar);

    if (structType == typeid(MyStruct)) {
        std::cout << "Variable is of type MyStruct." << std::endl;
    }
    else {
        std::cout << "Variable is not of type MyStruct." << std::endl;
    }

    if (classType == typeid(MyClass)) {
        std::cout << "Variable is of type MyClass." << std::endl;
    }
    else {
        std::cout << "Variable is not of type MyClass." << std::endl;
    }

    return 0;
}

在这个示例中,我们定义了一个自定义的结构体MyStruct和一个自定义的类MyClass。然后,我们分别创建了一个结构体变量structVar和一个类变量classVar。

使用typeid运算符,我们将结构体变量的类型信息存储在structType中,将类变量的类型信息存储在classType中。然后,我们可以将这些类型信息与自定义的结构体类型MyStruct和类类型MyClass进行比较,以确定变量的类型。

通过这种方式,我们可以判断变量是否为自定义的结构体或类,并根据需要执行相应的操作。请注意,这种方法要求自定义类型的名称必须是唯一的,以便与其他类型进行比较

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值