我有一个组件类,它定义了一般情况下应该如何创建Component的静态模板方法:classComponent{protected:uint32_tid;Component(uint32_tid):id(id){}templatestaticT*createComponent(){//contentherenotrelevantreturnnewT(someParameter);}};然后是一个实现,例如一个Button。这个类的构造函数不能直接使用,而是有一个调用Component::createComponent模板函数的静态方法。classButton:publicComponen
我创建了一个类,我想强制任何试图构建对象的人使用unique_ptr。为此,我考虑声明构造函数protected并使用返回unique_ptr的friend函数。所以这是我想做的一个例子:templateclassA{public:friendstd::unique_ptr>CreateA(intmyarg);protected:A(intmyarg){}};templatestd::unique_ptr>CreateA(intmyarg){//SinceIdeclaredCreateAasafriendIthoughtI//wouldbeabletodothatreturnstd::
这个问题在这里已经有了答案:关闭11年前。PossibleDuplicate:Differencebetweenprivate,publicandprotectedinheritanceinC++在C++中派生为protected或private有什么区别?我想不通,因为两者似乎都限制从派生类对象访问基类成员
#includeclassA{protected:voidfoo(){}};classB:publicA{public:voidbar(){std::cout这里我试图获取基类的protected成员函数的地址。我收到此错误。main.cpp:Inmemberfunction‘voidB::bar()’:main.cpp:5:error:‘voidA::foo()’isprotectedmain.cpp:13:error:withinthiscontextmake:***[all]Error1将foo更改为公共(public)工程。打印&B::foo也可以。能否请您解释一下为什么我们无
我想知道为什么下面的代码不能编译:classbase{protected:typedefvoid(base::*function_type)()const;voidfunction_impl()const{}//error:‘voidbase::function_impl()const’isprotected};classderived:publicbase{public:operatorfunction_type()const{returnboolean_test()==true?&base::function_impl:0;//error:withinthiscontext}pro
派生类可以在其ctor-initializer中调用protected基类构造函数,但仅限于其自己的基类子对象,而不能在其他地方调用:classBase{protected:Base(){}};classDerived:Base{Baseb;public:Derived():Base(),//OKb(){//errorBaseb2;//error}};标准对此有何规定?这是[class.protected]/1:AnadditionalaccesscheckbeyondthosedescribedearlierinClause11isappliedwhenanon-staticdata
考虑下面的例子classbase{protected:intx=5;int(base::*g);};classderived:publicbase{voiddeclare_value();derived();};voidderived::declare_value(){g=&base::x;}derived::derived():base(){}据了解,只有基类的friend和派生类可以访问基类的protected成员,但在上面的示例中,我得到以下错误"ErrorC2248'base::x':cannotaccessprotected在类中声明的成员但是当我添加以下行时friendcl
在以下代码中,使用Clang8.0.0+和-std=c++17编译,使用B{}创建派生类实例会报错错误:'A'类型的临时对象具有protected析构函数。当临时文件的类型为B(因此应该有一个公共(public)析构函数)时,为什么A会出现在此消息中?https://godbolt.org/z/uOzwYaclassA{protected:A()=default;~A()=default;};classB:publicA{//canalsoomitthese3lineswiththesameresultpublic:B()=default;~B()=default;};voidfoo(
如解释的那样,不允许在派生类中调用protected构造函数here.接受的答案解释说protected仅当A类的对象是B类的子对象。到目前为止,还不错。但是,为什么允许(至少在GCC4.6.3中)调用静态保护方法?具体来说,以下编译对我来说没有任何意义,而注释行则没有:classA{protected:A(){}staticAmakeA(){returnA();}};classB:publicA{public:staticAmakeAFromB(){returnmakeA();//compiles//returnA();//doesnotcompile}};从哲学上讲,构造函数非常类
为什么定义和提出protected和private继承?我知道在某些情况下可以使用私有(private)继承,但不推荐这样做。protected继承怎么样?谁能给我提供一种选择protected继承的情况?我很少看到这个。非常感谢! 最佳答案 私有(private)继承通常用于mixin——人们继承是为了从基类中获取功能,而不是因为“is-a”继承。protected继承也可以用于混合,其中混合功能也可用于下游类。 关于c++-protected继承,我们在StackOverflow上找