草庐IT

c++ - 如何初始化 const/non-const 静态引用成员?

classFoo{private:intm_i;public:Foo(inti):m_i(i){}};classFooA{private:conststaticFoo&m_foo;staticFoo&m_foo2;};Q1>如何初始化const静态引用?Q2>如何初始化非常量静态引用?注意:您可以对类FooA进行更改以说明这些方法。 最佳答案 以同样的方式初始化非引用static成员://Foo.cppconstFoo&FooA::m_foo=fooObj1;Foo&FooA::m_foo2=fooObj2;其中fooObj1和fo

c++ - const char myVar* 与 const char myVar[]

这个问题在这里已经有了答案:关闭11年前。PossibleDuplicate:Differencebetweenusingcharacterpointersandcharacterarrays有什么区别:constchar*myVar="HelloWorld!";constcharmyVar[]="HelloWorld!";如果有的话?

C++ 是否可以延迟常量静态成员的初始化?

我正在使用Qt,但这是一个通用的C++问题。我的情况很简单,我有一个Constants类,它有一个常量静态成员,我希望在进行某些函数调用后对其进行初始化。常量.h#ifndefCONSTANTS_H#defineCONSTANTS_HclassConstants{public:staticconstchar*constFILE_NAME;};#endif//CONSTANTS_H常量.cpp#include"constants.h"#includeconstchar*constConstants::FILE_NAME=QApplication::applicationFilePath(

c++ - const_cast 不适用于 C++?

这个问题在这里已经有了答案:Twodifferentvaluesatthesamememoryaddress(7个答案)关闭5年前。我有以下代码:constintk=1;int*p=const_cast(&k);cout(&k)=12;cout输出是:kbefore=1kafter=1为什么constcast在这里不起作用?

c++ - std::is_const 将 const 指针标识为非常量

我很困惑std::is_const识别const的行为指针为非const.我自己的实现is_const做完全一样的事情。我不确定为什么更通用的模板化结构正在挑选版本。gcc4.7和clang3.1-svn表现出相同的行为。任何人都可以解释发生了什么事吗?代码如下:#include#include#includeclassCEmptyClass{};namespacejbc{templatestructis_const:std::false_type{};templatestructis_const:std::true_type{};}intmain(intargc,char*argv[

c++ - 为什么当 typedef const 指针与 extra const 一起使用时编译器不报错?

以下给出了预期的错误:int*constconstp=newint;//g++error:duplicatecv-qualifier但下面没有给出任何错误,即使它等同于上面的错误:typedefint*constintp_const;intp_constconstp=newint;//ok!//^^^^^duplicate?为什么编译器会忽略额外的const?[注:intp_constconst与constchar*const不同,因为*p=;是可能的。] 最佳答案 在7.1.5[dcl.type](C++03)中,规定在通过typ

c++ - new 未调用,但已分配内存

我写了一个简单的Trie执行。这是源代码:#include#includetypedefunsignedintuint;classTrie{public:classNode{public:Node(constchar&_value);~Node();charget_value()const;voidset_marker(constuint&_marker);uintget_marker()const;booladd_child(Node*_child);Node*get_child(constchar&_value)const;voidclear();private:charm_val

c++ - 如何在 C++ 类中定义编译时(静态)常量?

我有一些常量只需要在编译时使用以简化代码,因此我不需要在运行时可用的实际变量。传统上这样做的方式是使用#defineNAME123,但我想要一个类型安全的替代方案。在类之外,您可以constintname=123;这很好用,但似乎不可能将它放在类中。例如这个:classExample{public:constdoubleusPerSec=1000000.0;};doubleusOneMinute=60*Tempo::usPerSec;适用于VisualC++,但不适用于GCC:error:non-staticconstmember‘constdoubleExample::usPerSe

运算符 == 的 C++ 模板类错误

错误:errorC2678:二进制“==”:没有找到接受类型为“constentry”的左手操作数的运算符(或者没有可接受的转换)函数:templateintindexList::search(constT&target)const{for(inti=0;iindexList.hindexList.cpp这应该是一个重载运算符吗?作为模板类,我不确定我是否理解错误?解决方案-类中的重载函数现在声明为const://Operatorsboolentry::operator==(constentry&dE)const 最佳答案 首先按原

c++ - 指向 const 的指针与通常的指针(对于函数)

指向const的指针和通常的函数指针之间有什么区别吗?什么时候适合对独立函数使用const限定符?我写了简短的示例来说明我的问题:#includeusingnamespacestd;intsum(intx,inty){returnx+y;}typedefintsum_func(int,int);intmain(){constsum_func*sum_func_cptr=∑//constfunctionsum_func*sum_func_ptr=∑//non-constfunction?//Whatisthedifferencebetweensum_func_cptran