我有一个变量,我更喜欢在cpp文件而不是头文件中声明。它应该只能被该类的对象访问。该变量应该为该类的每个对象都有一个单独的拷贝。继承不是必须的。通常,我会在类定义中声明它。嗯:classA{private:intnumber;}但是,我可以这样做吗?B.h:classB{private://nothing}B.cpp:staticintnumber; 最佳答案 不,如果您采用第二种方法,您会将其设为静态变量,这意味着您不会为该类的每个对象拥有不同的拷贝(它们将共享该变量)。无论哪种方式,如果它只应该被那个类访问,它应该放在类声明中,
“使用”私有(private)成员变量使其成为公共(public)成员,但构造函数保持私有(private)。示例:classMyClass;classBase{private:Base(floatv):m_v{v}{}floatm_v;friendMyClass;};classMyClass:publicBase{public:usingSuper=Base;usingSuper::Super;//thisisstillprivateusingSuper::m_v;//thisispublic};intmain(){MyClassx{3.4f};//error-callingapri
首先,一个演示问题的小例子:structBar{enumBaz{aa,bb,cc};Bazbaz_;operatorBaz()const{returnbaz_;}private:templateoperatorT()const;};intmain(){Barbar;switch(bar){caseBar::aa:break;caseBar::bb:break;caseBar::cc:break;default:break;}return0;}使用g++4.7.0编译此代码会出现以下错误:foo.cpp:Infunction‘intmain()’:foo.cpp:12:16:error:
这是我第一次在这里发帖。classBase{private:intbase;friendclassQuestion;};classDerived:publicBase{private:intsuper;};classQuestion{public:voidtest(Base&base,Derived&derived){intvalue1=base.base;//Noproblem,becauseQuestionisafriendclassofbaseintvalue2=derived.super;//Compileerror,becauseQuestionisnotafriendcla
在给定的C++代码中,DEF类的私有(private)成员在构造函数中初始化,并在友元函数中再次初始化。所以重定义会覆盖私有(private)变量还是构造函数给的值会一直存在?#include//classDEF;classABC{public:intfun(classDEF);};classDEF{private:inta,b,c;public:DEF():a(1),b(12),c(2){}friendintABC::fun(classDEF);/*Usingfriendfunctiontoaccesstheprivatememberofotherclass.*/voidfun_2(
哪一个编译器是正确的?classA{public:templatevoidfun(void(*f)()=funPrivate){}private:templatestaticvoidfunPrivate(){}};intmain(intargc,char**argv){Aa;a.fun();return0;}编译良好:gcc版本4.8.5(Ubuntu4.8.5-2ubuntu1~14.04.1)导致错误:clangversion3.4-1ubuntu3(tags/RELEASE_34/final)(basedonLLVM3.4)a.cpp:5:27:error:'funPrivate
我有一个关于C++的私有(private)继承的问题。请参见以下代码示例:#includeclassFoo{public:virtualvoiddoSomething(intvalue){std::cout目前,我不明白(或找不到正确的C++规范)为什么可以在Bar的构造函数中使用调用函数foobar>*this尽管是私有(private)继承。如果我尝试在main函数中使用Bar对象b调用foobar函数,编译器会给出错误正如预期的那样,因为私有(private)继承。我忽略的foobar(*this,42)和foobar(b,42)之间有什么区别? 最佳
这更像是一个C++标准问题。考虑以下代码:templateclasshas_Data{typedefcharone;typedeflongtwo;templatestaticonetest(typeof(&C::Data));templatestatictwotest(...);public:enum{value=sizeof(test(0))==sizeof(char)};};classMyClass{private:structData{};};voidfunction(boolval=has_Data::value){}以上代码适用于gcc(GCC)4.4.3但是clang版本3
我最近不得不做这样的事情:classA{};classB:privateA{};classC:publicB{public:A*myA;};intmain(){return0;}而且我在尝试的三个编译器中都遇到了错误。当我将myA的声明更改为::A*myA时,一切正常。我查阅了C++标准,发现第11.2节第3段说:Note:Amemberofaprivatebaseclassmightbeinaccessibleasaninheritedmembername,butaccessibledirectly.哪个相关,但不清楚。为什么名称A不可访问?如果不隐藏A会出现什么问题?谢谢,-本
我刚刚发现在C++中允许将私有(private)函数从基对象覆盖为公共(public)函数,因为VisualStudio会产生0警告。这样做有什么潜在的危险吗?如果没有,在基础对象中声明一个私有(private)的、protected和公共(public)的虚函数有什么区别? 最佳答案 what'sthedifferencebetweendeclaringavirtualfunctioninprivate,protectedandpublicinabaseobject?不同之处在于,private虚函数只能从基类中调用。如果该函数不