typeid是C++ 中的运算符。
句法:
typeid(type);
OR
typeid(expression);
参数: typeid 运算符接受一个参数,基于程序中使用的语法:
1. 当操作数是变量或对象时
// C++ program to show the use of typeid operator
#include
#include
using namespace std;
int main()
{
int i, j;
char c;
// Get the type info using typeid operator
const type_info& ti1 = typeid(i);
const type_info& ti2 = typeid(j);
const type_info& ti3 = typeid(c);
// Check if both types are same
if (ti1 == ti2)
cout << "i and j are of"
<< " similar type" << endl;
else
cout << "i and j are of"
<< " different type" << endl;
// Check if both types are same
if (ti2 == ti3)
cout << "j and c are of"
<< " similar type" << endl;
else
cout << "j and c are of"
<< " different type" << endl;
return 0;
}
输出
i and j are of similar type
j and c are of different type
2. 当操作数是表达式时
// C++ program to show the use of typeid operator
#include
#include
using namespace std;
int main()
{
int i = 5;
float j = 1.0;
char c = 'a';
// Get the type info using typeid operator
const type_info& ti1 = typeid(i * j);
const type_info& ti2 = typeid(i * c);
const type_info& ti3 = typeid(c);
// Print the types
cout << "ti1 is of type "
<< ti1.name() << endl;
cout << "ti2 is of type "
<< ti2.name() << endl;
cout << "ti3 is of type "
<< ti3.name() << endl;
return 0;
}
输出:
ti1 is of type f
ti2 is of type i
ti3 is of type c