所以thisanswer让我想到了将new的结果分配给指向const的指针的场景。AFAIK,在这种情况下,您没有理由不能合法const_castconstness并实际修改对象:structX{intx;};//....constX*x=newX;const_cast(x)->x=0;//okay但后来我想-如果你真的想要new创建一个const对象怎么办。所以我尝试了structX{};//....constX*x=newconstX;它编译好了!!!这是GCC扩展还是标准行为?我在实践中从未见过这种情况。如果它是标准的,我会尽可能开始使用它。 最佳答案
所以thisanswer让我想到了将new的结果分配给指向const的指针的场景。AFAIK,在这种情况下,您没有理由不能合法const_castconstness并实际修改对象:structX{intx;};//....constX*x=newX;const_cast(x)->x=0;//okay但后来我想-如果你真的想要new创建一个const对象怎么办。所以我尝试了structX{};//....constX*x=newconstX;它编译好了!!!这是GCC扩展还是标准行为?我在实践中从未见过这种情况。如果它是标准的,我会尽可能开始使用它。 最佳答案
我的代码相当于以下内容:constint*constn=newint;printf("input:");scanf("%d",n);deleten;现在,由于n是一个指向CONSTANT整数的指针,这应该不起作用(我期待编译器错误)。但是,这似乎可以正常工作,甚至将输入的值存储到*n中。我想知道,为什么这不会给我一个错误;为什么它起作用?scanf不应该不能改变*n的值吗? 最佳答案 scanf的原型(prototype)是:intscanf(constchar*format,...);省略号表示它接受可变参数。C(和C++)没有办
我的代码相当于以下内容:constint*constn=newint;printf("input:");scanf("%d",n);deleten;现在,由于n是一个指向CONSTANT整数的指针,这应该不起作用(我期待编译器错误)。但是,这似乎可以正常工作,甚至将输入的值存储到*n中。我想知道,为什么这不会给我一个错误;为什么它起作用?scanf不应该不能改变*n的值吗? 最佳答案 scanf的原型(prototype)是:intscanf(constchar*format,...);省略号表示它接受可变参数。C(和C++)没有办
通常当你的类中有一个常量私有(private)成员变量时,它只有一个getter而没有setter,它看起来像这样://Example.hclassExample{public:Example(constintvalue);constintgetValue()const;private:constintm_value;};//Example.cpp#include"Example.h"Example::Example(constintvalue):m_value(value){}constintExample::getValue()const{returnm_value;}现在我要做的
通常当你的类中有一个常量私有(private)成员变量时,它只有一个getter而没有setter,它看起来像这样://Example.hclassExample{public:Example(constintvalue);constintgetValue()const;private:constintm_value;};//Example.cpp#include"Example.h"Example::Example(constintvalue):m_value(value){}constintExample::getValue()const{returnm_value;}现在我要做的
在我维护的一个项目中,我看到很多简单的get/set方法的代码constint&MyClass::getFoo(){returnm_foo;}voidMyClass::setFoo(constint&foo){m_foo=foo;}这样做的意义何在?intMyClass::getFoo(){returnm_foo;}//Removed'const'and'&'voidMyClass::setFoo(constintfoo){m_foo=foo;}//Removed'&'传递对原始类型的引用应该需要与传递类型的值本身相同(或更多)的工作,对吧?毕竟只是一个数字……这只是一些尝试的微优化还
在我维护的一个项目中,我看到很多简单的get/set方法的代码constint&MyClass::getFoo(){returnm_foo;}voidMyClass::setFoo(constint&foo){m_foo=foo;}这样做的意义何在?intMyClass::getFoo(){returnm_foo;}//Removed'const'and'&'voidMyClass::setFoo(constintfoo){m_foo=foo;}//Removed'&'传递对原始类型的引用应该需要与传递类型的值本身相同(或更多)的工作,对吧?毕竟只是一个数字……这只是一些尝试的微优化还
听说临时对象只能分配给常量引用。但是这段代码出错了#includetemplatetconst&check(){returnt();//returnatemporaryobject}intmain(intargc,char**argv){constint&resCheck=check();/*fine*/typedefint&ref;constreferror=check();/*error*/return0;}得到的错误是invalidinitializationofreferenceoftype'int&'fromexpressionof'constint'
听说临时对象只能分配给常量引用。但是这段代码出错了#includetemplatetconst&check(){returnt();//returnatemporaryobject}intmain(intargc,char**argv){constint&resCheck=check();/*fine*/typedefint&ref;constreferror=check();/*error*/return0;}得到的错误是invalidinitializationofreferenceoftype'int&'fromexpressionof'constint'