我有一个代码,我想使用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;
}
答案 0 :(得分:1)
#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