这个在面试中被问到了。如何编写自己的dynamic_cast。我想,基于typeid的name函数。现在如何实现自己的typid?我对此一无所知。 最佳答案 你没有任何线索是有原因的,dynamic_cast和static_cast不像const_cast或reinterpret_cast,它们实际上执行指针运算并且在某种程度上是类型安全的。指针运算为了说明这一点,请考虑以下设计:structBase1{virtual~Base1();chara;};structBase2{virtual~Base2();charb;};struc
我的代码有问题。在Xcode或使用C++11编译器中,此代码运行良好。但是,当我将此代码提交给在线法官时,判决显示“编译错误”。我认为他们使用的是C++4.7.1编译器,当我尝试编译它(使用Ideone)时,它说:prog.cpp:Infunction'voidprintArray(int)':prog.cpp:27:error:'void*'isnotapointer-to-objecttypeprog.cpp:27:error:'void*'isnotapointer-to-objecttypeprog.cpp:27:error:'void*'isnotapointer-to-ob
我在2个不同的文件中有2个类:正则矩阵.h:#ifndef_RM_H#define_RM_H#include"SparseMatrix.h"...classRegMatrix{...RegMatrix(constSparseMatrix&s){...}//ctor...};#endif稀疏矩阵.h:#ifndef_SM_H#define_SM_H#include"RegMatrix.h"...classSparseMatrix{...SparseMatrix(constRegMatrix&r){...}//ctor...};#endif在构造函数行上我得到了错误:错误C4430:缺少类
我看到一本关于C++的书提到使用静态转换在继承层次结构中导航比使用动态转换更有效。例子:#include#includeusingnamespacestd;classShape{public:virtual~Shape(){};};classCircle:publicShape{};classSquare:publicShape{};classOther{};intmain(){Circlec;Shape*s=&c;//Upcast:normalandOK//Moreexplicitbutunnecessary:s=static_cast(&c);//(Sinceupcastingis
我遇到了这个:structBase{void*operatornew(size_t);voidoperatordelete(void*);virtual~Base(){}//(p);if(dynamic_cast(pB)!=0){/*...NOTreachinghere?...*/}free(p);}现在如果我们这样做,Base*p=newDerived;deletep;令人惊讶的是,conditioninsidetheBase::deleteisnotsatisfied我做错了什么吗?或者从void*进行转换会丢失Derived*的信息? 最佳答案
在开始之前,我必须首先声明,我已经研究过针对此错误的可能解决方案。不幸的是,它们都与不使用数组有关,这是我项目的要求。另外,我目前正在学习CS入门类(class),所以我的经验几乎没有。数组的用途是从文件中收集名称。因此,为了初始化数组,我计算了名称的数量并将其用作大小。问题是标题中所述的错误,但我仍然使用一维数组时看不到解决方法。主要.cpp#include#include#include#include#include#include"HomeworkGradeAnalysis.h"usingnamespacestd;intmain(){ifstreaminfile;ofstrea
根据关于可见性的gccwiki(https://gcc.gnu.org/wiki/Visibility,请参阅“C++异常问题(请阅读!)”)部分,但似乎也是一个示例(dynamic_castfailedwhenhidingsymbol),隐藏类可以导致有效的dynamic_cast失败。我想通过示例准确了解这种情况何时发生:任何人都可以给我一个小示例来正确理解效果吗?这是我的尝试和理解(在Linux上使用gcc>7):据我了解,我需要的是vaguelinkage发生,当基类没有关键方法时发生。所以我尝试了这个基本层次结构:classA{virtual~A();virtualvoidp
环境:MicrosoftVisualStudio2010withSP1Preminum(10.0.40219.1SP1Rel),WindowsXPSP3VC10编译器支持auto关键字,但推导的类型相关信息对于枚举似乎并不总是正确的。例子:#includeenumfruit_t{apple=100,banana=200,};intmain(){constautopa=newauto(banana);constautopb=newfruit_t(banana);static_assert(std::is_same::value,"notsame!");deletepb;deletepa;
我一直在研究一个链表模板类来对各种变量做同样的事情,并设法解决了大部分问题。除了编译时,我得到这些:g++-Wall-otemplate_testtemplate_test.cppInfileincludedfromtemplate_test.cpp:1:0:LinkedList.h:50:11:error:declarationof‘classType’LinkedList.h:7:11:error:shadowstemplateparm‘classType’LinkedList.h:51:30:error:invaliduseofincompletetype‘classLinked
我在最新版本的Xcode(撰写本文时为9.4.1)中构建了一个C++框架,我再次在Xcode中从Objective-C++代码中使用它。我需要执行从一种指针类型到另一种指针类型的dynamic_cast。但是,dynamic_cast仅适用于调试版本,不适用于发布版本。关于dynamic_cast在Objective-C++中的工作方式,我是否缺少或理解导致此示例失败的某些内容?C++框架TestClass.hppclassParent{public://https://stackoverflow.com/a/8470002/3938401//musthaveatleast1virtu