我试图让下面的代码工作,但我找不到关于C++如何处理公共(public)继承和私有(private)继承的足够好的文档来让我做我想做的事。如果有人可以解释为什么我不能使用私有(private)继承或Parent::size访问Parent::setSize(int)或Parent::size>使用公共(public)继承。要解决这个问题,我需要在Parent中使用getSize()和setSize()方法吗?classParent{private:intsize;public:voidsetSize(ints);};voidParent::setSize(ints){size=s;}c
这个问题在这里已经有了答案:canyouaccessprivatemembervariablesacrossclassinstances?(2个答案)关闭9年前。我在使用C++的信号类中有这个项目。当我看到这个时,我正在修改我们的教师代码:ListData::ListData(constListData&newlist):Data(),nbNodes(newlist.nbNodes){}正如他所说,这是一个“复制构造函数”,应该大致等同于以下内容:ListData::ListData(constListData&newlist){Data="";//copynbNodesofnewLi
我有一个名为Cal的类,它是.cpp和.h的对应物头文件有classCal{private:intwa[2][2];public:voiddo_cal();};.cpp文件有#include"Cal.h"voidCal::do_cal(){print(wa)//whereprintjustitteratesandprintstheelementsinwa}我的问题是如何初始化数组wa?我似乎无法让它工作。我试过:intwa[2][2]={{5,2},{7,9}};在头文件中,但我收到错误消息说我不能这样做,因为它反对iso..something。还尝试在构造函数中初始化数组wa但这也不
当我尝试编译以下内容时:#includeclassTest{public:void*operatornew(size_tnum);voidoperatordelete(void*test);~Test();private:Test();};Test::Test(){std::cout(test));}intmain(){Test*test=newTest;deletetest;}我明白了:$g++-otesttest.cpptest.cpp:Infunction‘intmain()’:test.cpp:14:error:‘Test::Test()’isprivatetest.cpp:3
我有一个变量,我更喜欢在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