C/C++ 判断一个变量的类型(typeid)
Posted cpp_learner
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C/C++ 判断一个变量的类型(typeid)相关的知识,希望对你有一定的参考价值。
当有某一个变量,你不知道他是什么类型,且你有需要知道他是什么类型时,就可以使用typeid关键字进行判断!
操作如下:
-
判断int类型
int in = 10; if (typeid(in) == typeid(int)) { cout << "This '" << in << "' is a int!" << endl; }
-
判断类
// 类 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关键字的其中一个用法列举出来,其实他还有很多其它高级用法, 有兴趣的可以自行去了解了解!
以上是关于C/C++ 判断一个变量的类型(typeid)的主要内容,如果未能解决你的问题,请参考以下文章
C/C++杂记:运行时类型识别(RTTI)与动态类型转换原理