📜  C++中带有示例的typeid运算符

📅  最后修改于: 2021-05-30 18:48:01             🧑  作者: Mango

typeid是C++中的运算符。

  • 它用于需要对象的动态类型或运行时类型信息的地方。
  • 它包含在库中。因此,为了使用typeid,该库应包含在程序中。
  • typeid表达式是一个左值表达式。

句法:

typeid(type);
OR
typeid(expression);

参数: typeid运算符根据程序中使用的语法接受参数:

  • type :当需要变量或对象的运行时类型信息时,将传递此参数。在这种情况下,不需要在类型内部进行评估,而只需知道类型信息即可。
  • expression:当需要表达式的运行时类型信息时,将传递此参数。在这种情况下,首先对表达式求值。然后,提供最终结果的类型信息。

返回值:该运算符提供指定参数的运行时类型信息,并因此返回该类型信息,以作为对type_info类的对象的引用。
用法: typeid()运算符根据操作数类型以不同方式使用。

  1. 当操作数是变量或对象时。
CPP
// 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;
}


CPP
// 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;
}


输出:
i and j are of simiar type
j and c are of different type
  1. 当操作数是一个表达式时。

CPP

// 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”