C/C++ 判断一个变量的类型(typeid)

当有某一个变量,你不知道他是什么类型,且你有需要知道他是什么类型时,就可以使用typeid关键字进行判断!

操作如下:

  1. 判断int类型

    int in = 10;
    if (typeid(in) == typeid(int)) {
    	cout << "This '" << in << "' is a int!" << endl;
    }
    
  2. 判断类

    // 类
    Student stu("小明");
    if (typeid(stu) == typeid(Student)) {
    	cout << "This '" << stu.name << "' is a Student!" << endl;
    }
    

当然你也还可以 判断其它类型这里就不列举了!

来说说具体改怎么使用:

double dou = 3.14;
if (typeid(dou) == typeid(int)) {
	cout << "This '" << dou << "' is a int!" << endl;
	
} else if (typeid(dou) == typeid(string)) {
	cout << "This '" << dou << "' is a string!" << endl;
	
} else if (typeid(dou) == typeid(double)) {
	cout << "This '" << dou << "' is a double!" << endl;

} else {
	cout << "This '" << dou << "' is not!" << endl;
}

用法如上,使用多个if else做逻辑处理,就可以得到想要的变量是什么类型了!


全部测试代码:

#include <iostream>
#include <string>

using namespace std;

class Student {

public:
	Student(string _name = "无名字") {
		this->name = _name;
	}
	~Student() { }

public:
	string name;
};


typedef struct Struct {
	int count = 10;
};


int main(void) {
	
	// 整形
	int in = 10;
	if (typeid(in) == typeid(int)) {
		cout << "This '" << in << "' is a int!" << endl;
	}
	
	// 字符串
	string str = "abc";
	if (typeid(str) == typeid(string)) {
		cout << "This '" << str << "' is a string!" << endl;
	}

	// 字符
	char c = 'c';
	if (typeid(c) == typeid(char)) {
		cout << "This '" << str << "' is a char!" << endl;
	}

	// 类
	Student stu("小明");
	if (typeid(stu) == typeid(Student)) {
		cout << "This '" << stu.name << "' is a Student!" << endl;
	}

	// 结构体
	typedef struct Struct structs;
	if (typeid(structs) == typeid(Struct)) {
		cout << "This 'structs' is a Struct!" << endl;
	}



	double dou = 3.14;
	if (typeid(dou) == typeid(int)) {
		cout << "This '" << dou << "' is a int!" << endl;
	
	} else if (typeid(dou) == typeid(string)) {
		cout << "This '" << dou << "' is a string!" << endl;
	
	} else if (typeid(dou) == typeid(double)) {
		cout << "This '" << dou << "' is a double!" << endl;

	} else {
		cout << "This '" << dou << "' is not!" << endl;
	}

	return 0;
}

运行截图:
在这里插入图片描述


总结:

用法还是很简单的,不过,我这里只是简单将typeid关键字的其中一个用法列举出来,其实他还有很多其它高级用法, 有兴趣的可以自行去了解了解!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpp_learners

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值