C++判断变量/对象/枚举类型的简单方式

本文详细介绍了C++中的typeid操作符,用于获取变量的类型信息,并通过示例展示了如何判断变量类型。同时,提到了typeid().name()方法获取类型名,但其返回的名称通常不是直观的字符串。通过示例代码演示了如何检查不同类型的变量,如int、char、string和自定义结构体类型。
摘要由CSDN通过智能技术生成

关键点

  • <typeinfo>

使用typeid()操作符所需包含的头文件。

  • typeid()

获取变量类型信息的操作符,其返回值类型为std::typeinfo。我们可使用typeid(n) == typeid(int)的方式来判断变量n是否为类型int

注:可以使用typeid().name()获取变量类型名,但通常都不是我们所熟知的类型名称,而且比较奇怪的字符串,比如int类型,得到的name()i

示例

#include <typeinfo>
#include <iostream>
#include <string>
using namespace std;


struct Hero
{
        int age;
        string name;
};

enum Color
{
        Red,
        Blue
};


int main()
{
        int n = 666;
        char c = 'c';
        string str = "Hello World";
        Hero hero;
        Color color;

        if (typeid(n) == typeid(int)) cout << "n is an integer\n";
        if (typeid(c) == typeid(char)) cout << "c is a character\n";
        if (typeid(str) == typeid(string)) cout << "str is a string\n";
        if (typeid(hero) == typeid(Hero)) cout << "hero is a Hero\n";
        if (typeid(color) == typeid(Color)) cout << "color is a Color\n";
}

编译代码后运行,所得结果为:

n is an integer
c is a character
str is a string
hero is a Hero
color is a Color
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值