使用typeid关键字C ++

时间:2015-04-04 14:09:46

标签: c++ class

我有一个代码,我想使用typeid关键字显示数组指针的类类型,但是当我写cout <<typeid (Food[1]);编译错误时!错误:没有运算符“&lt;&lt;”匹配这些操作数,操作数类型是:std :: ostream&lt;

class food{
public:
    string getkind(){
        return kind;
    }
    virtual void setkind(){
    kind = "Apple";
    }
    // complete the set functions
private:
    string  kind;

};
int main()
{
    food *Food[3];
    derived1 obj1;
    derived2 obj2;
    derived3 obj3;
    Food[0]=&obj1;
    Food[1] = &obj2;
    Food[2] = &obj3;
    cout << typeid (food[1]);//Error ! Why? 


    system("Pause");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

MCVE

#include <iostream>
#include <typeinfo>

class X {};

int main() {
    std::cout << typeid(X) << "\n";
}

错误消息:

foo.cc:7:15: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'const std::type_info')
    std::cout << typeid(X) << "\n";
    ~~~~~~~~~ ^  ~~~~~~~~~

修正:

typeid(X)会返回std::type_info个对象。它有一个名为name的非常有用的命名方法。

更好的代码:

#include <iostream>
#include <typeinfo>

class X {};

int main() {
    std::cout << typeid(X).name() << "\n";
}

更好的输出(实施定义):

1X