我特别想到策略模式(设计模式,GoF94),其中建议传递给策略构造函数的上下文可以是包含策略(作为成员)本身的对象。但以下内容不起作用://analysis.hclassStrategyBase;classStrategy1;classStrategy2;classAnalysis{...voidChooseStrategy();private:StrategyBase*_s;...};//analysis.cppvoidAnalysis::ChooseStrategy(){if(...)_s=newStrategy1(this);elseif(...)_s=newStrategy2(
据我了解,[=]复制函数体内使用的所有变量,而[this]仅复制this指针。但是查看示例,我发现[=]被广泛使用,其中[this]或[this,foo]就足够了。是否有任何理由(例如性能提升)使用[this]而不是[=]? 最佳答案 没有性能提升,因为正如您所说,只有您在lambda中实际使用的变量会被复制用于[=]。†这主要是编码人员的懒惰和保持lambda头的简洁。如果您使用新变量,则必须扩展捕获子句以包含这些变量,等等。然而,有时,您希望/必须是明确的,例如当您想要混合按引用和按值捕获时。†请注意,目前,以下代码段中的[=]
为什么这段代码会产生错误的输出?//this-type.cpp#include#includeusingnamespacestd;templateclassA{public:A(){cout>::value{};intmain(){Bb;}输出:$g++-std=c++11this-type.cpp$./a.outfalseA到B中的“*this”的类型是A,不是吗? 最佳答案 *this是A类型的左值,因此decltype(*this)将给出引用类型A&。回想一下左值上的decltype给出了引用类型:cout>::value&>
对于类X的非const成员函数,this指针的类型为X*const。然后,成员函数的this指针始终为const。那么,我们是否总是需要像这样进行const转换:voidfoo::p(){const_cast(member)=1;}我是不是漏掉了什么? 最佳答案 ForanonconstmemberfunctionofclassX,thispointerisoftypeX*const.不,非const成员函数中的this指针的类型只是X*(而且它是一个右值)。但即使this是X*const,这仍然不会阻止您更改数据成员。您的代码示例
假设我有以下类(class):classfoo{public:intsomeNum;voidcalculation(intsomeNum);};定义:voidfoo::calculation(intsomeNum){someNum=someNum;}现在在someNum=someNum行中,指的是哪个someNum?如果我这样做:this->someNum=someNum那第二个someNum是什么?避免这个问题的好的命名风格是什么?例如,在objective-c中,在成员变量名前加上前缀“_”。(例如:_someNum); 最佳答案
这个问题在这里已经有了答案:Whatistheusefulnessof`enable_shared_from_this`?(6个答案)关闭6年前。我是C++11的新手,我遇到了enable_shared_from_this。我不明白它试图达到什么目的?所以我有一个使用enable_shared_from_this的程序。structTestCase:enable_shared_from_this{std::shared_ptrgetptr(){returnshared_from_this();}~TestCase(){std::coutobj1(newTestCase);std::sh
假设我有一个结构structFoo{voidbar(){do_baz(this);}/*Seeeditbelowvoiddo_baz(Foo*&pFoo){pFoo->p_sub_foo=newFoo;//forexample}*/Foo*p_sub_foo;}GCC告诉我temp.cpp:Inmemberfunction‘voidFoo::bar()’:temp.cpp:3:error:nomatchingfunctionforcallto‘Foo::do_baz(Foo*const)’temp.cpp:5:note:candidatesare:voidFoo::do_baz(Foo
我正在阅读一些C++文本。在一个例子中,文本写成:classStudent{intno;chargrade[M+1];public:Student();Student(int,constchar*);constStudent&set(int,constchar*);voiddisplay()const;};Student::Student(){no=0;grade[0]='\0';}Student::Student(intn,constchar*g){*this=Student();//initializetoemptyset(n,g);//validate,resetifok}我不明
我在以下代码中调用RegisterClassEx时收到一个类已存在的错误。此代码在类构造函数中:this->m_wcx.cbSize=sizeof(WNDCLASSEX);//sizeofstructurethis->m_wcx.style=CS_HREDRAW|CS_VREDRAW;//initiallyminimizedthis->m_wcx.lpfnWndProc=&WndProc;//pointstowindowprocedurethis->m_wcx.cbClsExtra=0;//noextraclassmemorythis->m_wcx.cbWndExtra=0;//noe
这个问题在这里已经有了答案:Inthisspecificcase,isthereadifferencebetweenusingamemberinitializerlistandassigningvaluesinaconstructor?(12个答案)关闭9年前。我只是浏览Cprogramming.com上的随机页面并注意到ConstructorsandDestructors教程/示例页面。他们使用了以下定义构造函数的方法:classString{private:char*str;intsize;public:String():str(NULL),size(0){}//我一直在使用构造函