如果我有三个类(class),A、B、C。A和B是friend(双向)。此外,B和C是friend(双向)。A有指向B的指针,B有指向C的指针,为什么A不能通过指针访问C的私有(private)数据?澄清一下:这是一个纯理论C++语言问题,而不是设计建议问题。 最佳答案 C++中的友元是不可传递的:约翰是我的一个friend,他可以随时使用我的无线连接(我相信他)。约翰的friend蒂姆虽然是个废物,虽然约翰是我的friend,但我没有把蒂姆列为friend,因此我不让他使用我的无线连接。友元不会遗传另外,约翰的child是一群流氓
classx{voidxx(){}};classy{friendvoidx::xx();};这会导致类似的错误error:friendfunction'xx'isaprivatememberof'x'为什么我不能将私有(private)成员函数声明为另一个类的friend? 最佳答案 [class.friend]/9:Anamenominatedbyafrienddeclarationshallbeaccessibleinthescopeoftheclasscontainingthefrienddeclaration.原因很简单;p
这个问题在这里已经有了答案:Howdowedeclareafriendfunctionwithaclasstemplateinto.hfileanddefinethemintoa.cppfile(notallinoneheaderfile)?(1个回答)关闭5个月前。我正在尝试将运算符frienddeclarationstd::ostream&operator&v)declaresanontemplatefunction对于此代码:friendostream&operator&);它给出了第二个警告作为建议ifthisisnotwhatyouintended,makesurethefu
这是一个关于returntypededuction的小实验对于在链接的工作文件中没有记录的类内友元函数(在两种情况下使用Clang3.4SVN和g++4.8.1和std=c++1y)#includestructA{inta_;friendautooperator==(Aconst&L,Aconst&R){returnL.a_==R.a_;//a_isoftypeint,soshouldreturnbool}};templatestructB{intb_;friendautooperator==(Bconst&L,Bconst&R){returnL.b_==R.b_;//b_isofty
在一些书籍和互联网上,我经常看到“operator==应该被声明为friend”之类的建议。我应该如何理解何时必须将运算符声明为友元以及何时应将其声明为成员?除了==之外,哪些运算符最常需要声明为好友?和? 最佳答案 这实际上取决于类是位于调用operator==(或其他运算符)的左侧还是右侧。如果一个类将在表达式的右侧——并且不提供到可以与左侧比较的类型的隐式转换——你需要实现operator==作为单独的函数或作为类的friend。如果运算符(operator)需要访问私有(private)类数据,必须声明为friend。例如,
在类中定义的友元函数的完全限定名是什么?我最近看到了一个类似于以下的示例。下面val()的全称是什么?#includenamespacefoo{classA{intx;public:A(intx=0):x(x){}friendintval(constA&a){returna.x;}};}intmain(){foo::Aa(42);//val()foundusingADL:std::cout依赖于参数的查找是找到val()的唯一方法吗?诚然,这并非源于实际问题。我只是希望获得更好的理解。 最佳答案 Isargument-depende
假设我有一个类F应该是类G(在全局命名空间中)和C(在命名空间A)。要成为A::C的friend,F必须前向声明。要成为G的friend,F的前向声明是不必要的。同样,类A::BF可以成为A::C的friend,无需前向声明以下代码说明了这一点,并可以使用GCC4.5、VC++10以及至少一个其他编译器进行编译。classG{friendclassF;intg;};//withoutthisforwarddeclaration,Fcan'tbefriendtoA::CclassF;namespaceA{classC{friendclass::F;friendclassBF;intc;}
当一个lambda函数在C类的友元函数F中声明时,该lambda函数是否可以访问C私有(private)成员(member)?具体来说,标准允许吗? 最佳答案 C++11§[expr.prim.lambda]5.1.2/3:Thetypeofthelambda-expression(whichisalsothetypeoftheclosureobject)isaunique,unnamednon-unionclasstype—calledtheclosuretype—whosepropertiesaredescribedbelow.
当一个lambda函数在C类的友元函数F中声明时,该lambda函数是否可以访问C私有(private)成员(member)?具体来说,标准允许吗? 最佳答案 C++11§[expr.prim.lambda]5.1.2/3:Thetypeofthelambda-expression(whichisalsothetypeoftheclosureobject)isaunique,unnamednon-unionclasstype—calledtheclosuretype—whosepropertiesaredescribedbelow.
我有一个类模板Obj和一个函数模板make_obj。Obj定义了一个private单个构造函数,该构造函数采用对其模板化类型的引用来绑定(bind)。templateclassObj{private:T&t;Obj(T&t):t{t}{}};templateObjmake_obj(T&t){return{t};}我想要的是将make_obj函数声明为friend以便它可以创建Obj的,但没有其他人可以(除了通过复制ctor)。我尝试了几个friend声明,包括friendObjmake_obj(T&);和templatefriendObjmake_obj(T2&);后者在使Obj类的所