我无法正确获取typeid函数.
我错过了什么
码:
class A
{
public:
int a1;
A()
{
}
};
class B: public A
{
public:
int b1;
B()
{
}
};
int main()
{
B tempb;
A tempa;
A * ptempa;
ptempa = &tempb;
std::cout << typeid(tempb).name() << std::endl;
std::cout << typeid(tempa).name() << std::endl;
std::cout << typeid(*ptempa).name() << std::endl;
return 0;
}
它始终打印:
B级
A级
A级
我正在为我的项目使用VS2010
解决方法:
它指向的对象必须是多态的,以便按预期工作.如果A有虚拟方法而不是代码可以按预期工作,例如添加虚拟析构函数,即demo live here using gcc.
引用形式C++ draft standard部分5.2.8型号识别第2段说:
When typeid is applied to a glvalue expression whose type is a
polymorphic class type (10.3), the result refers to a std::type_info
object representing the type of the most derived object (1.8) […]
这适用于我们有虚拟方法的情况,在您的情况下,您没有多态类型,因此第3段适用:
When typeid is applied to an expression other than a glvalue of a
polymorphic class type, the result refers to a std::type_info object
representing the static type of the expression
所以你将获得静态类型,即A.
只是为了更完整一节10.3虚拟功能说:
Virtual functions support dynamic binding and object-oriented
programming. A class that declares or inherits a virtual function is
called a polymorphic class.
标签:typeid,c 来源: https://codeday.me/bug/20191008/1870564.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。