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

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

#include

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关键字的其中一个用法列举出来,其实他还有很多其它高级用法, 有兴趣的可以自行去了解了解!

🌟 相关推荐

Visual Studio 2015的安装与基本使用
如何打开mobile365

Visual Studio 2015的安装与基本使用

📅 07-07 👀 5090
中國十大雲端服務供應商:面向企業、小型企業、技術開發人員和可擴展雲端解決方案的最佳平台
下列哪幅名作不属于昂布罗休美术馆的馆藏
best365官网下载

下列哪幅名作不属于昂布罗休美术馆的馆藏

📅 06-27 👀 2969