这是我的第一个问题:)我有一堆文件,我打开它如下图所示;ifstreamin(filename,ios::binary|ios::in)然后,我希望在unsignedinthold中保存2个字节的数据;unsignedinthold;in.read(static_cast(&hold),2);这对我来说似乎是正确的。但是,当我用编译它时g++-ansi-pedantic-errors-Werror--Wall-omainmain.cpp编译器报错error:invalidstatic_castfromtype‘unsignedint*’totype‘char*’其实我已经通过将stat
#include"iostream"classA{private:inta;public:A():a(-1){}intgetA(){returna;}};classA;classB:publicA{private:intb;public:B():b(-1){}intgetB(){returnb;}};intmain(){std::auto_ptra=newA();std::auto_ptrb=dynamic_cast>(a);return0;}错误:不能dynamic_cast`(&a)->std::auto_ptr::get()const 最佳答案
我想写这样的东西,不能编译:std::vectoras;std::vectorbs(as.size());std::transform(as.beginn(),as.end(),bs.begin(),boost::lexical_cast);但这行不通,所以我创建了一个仿函数来为我做这件事:templatestructlexical_transform{templateDestoperator()(constSrc&src)const{returnboost::lexical_cast(src);}};有更简单的方法吗? 最佳答案
我刚遇到thisexample:向下滚动到页面底部,您会在此处找到QWidget*pw=static_cast(parent);Parent的类型为:QObject,它是QWidget的基类,所以在这种情况下,不是:应该使用dynamic_cast吗?例如:QWidget*pw=dynamic_cast(parent)谢谢, 最佳答案 如果您知道您是从基类向下转型到子类(即,您知道该对象实际上是子类的一个实例),那么static_cast是完全合法的(并且性能更高)。 关于c++-诺基亚
我有这个测试片段#include#include#include#include#includeclasswrapper{intvalue;charcharacter;std::stringstr;public:wrapper(inti,charc,std::strings){value=i;character=c;str=s;}voidget_data(){std::coutcontainer;container.push_back(10);container.push_back(1.4);container.push_back("Mayukh");container.push_ba
为什么以下内容需要C风格的转换?int*ptr=static_cast(0xff);//error:invalidstatic_castfromtype'int'//totype'int*'int*ptr=(int*)0xff;//ok. 最佳答案 static_cast只能在两个相关类型之间进行转换。整数与指针无关,反之亦然,因此您需要改用reinterpret_cast,它告诉编译器重新解释整数的位,就好像它们是指针(反之亦然):int*ptr=reinterpret_cast(0xff);阅读以下内容了解更多详情:Typeco
这个问题在这里已经有了答案:behaviorofconst_castinC++[duplicate](3个答案)关闭8年前。这里发生了什么?constinta=0;constint*pa=&a;int*p=const_cast(pa);*p=1;//undefinedbehavior??cout我的编译器输出0和1,但是“a”的地址和“p”的值是相同的,所以我很困惑这怎么可能。
我想重新解释将函数指针转换为void*变量。函数指针的类型将为Class*(*)(void*)。下面是示例代码,classTest{inta;};intmain(){Test**p(void**a);void*f=reinterpret_cast(p);}以上代码适用于VisualStudio/x86编译器。但是使用ARM编译器,它会给出编译错误。不知道为什么。Error:#694:reinterpret_castcannotcastawayconstorothertypequalifiers我阅读了Castingafunctionpointertoanothertype中的解释我担心
例如提议maphold其中void*总是存储来自classA的指针稍后通过static_cast将其投回是否安全?classA*ptr=static_cast(holditerator->second);原因void*使用是因为hold是在某些不知道什么的cpp文件使用的header上定义的类的成员classA是。我必须包括classA的标题这些cpp文件的定义由于许多原因而无法完成。 最佳答案 是的,static_cast在那种情况下是可以的,并且是正确的使用方式。不过,我不得不问您为什么不首先存储classA*指针。如果你想将派
在C++中,我试图打印C字符串的地址,但我的转换似乎存在一些问题。我从一本书中复制了代码,但它无法在我的Mac上编译。constchar*constword="hello";cout(word) 最佳答案 你正试图抛弃“常量”:word指向常量数据,但static_cast的结果不是指向常量数据的指针。static_cast不会让你那样做的。你应该使用static_cast相反。 关于c++-不允许从'constchar*'到'void*'的static_cast,我们在StackOve