虽然类友元是C++的最后手段之一,但这种模式有意义吗?classPeer{public:friendclassPeer;voidGetSecret(constPeer&other){conststd::string&secret=other.GiveSecret();std::coutOk这个模式的原因是因为Peer都是同级别的,他们需要在彼此之间共享知识,但是这个知识是secret的,因为除了peer之外没有人应该使用它,或者程序是不再有效。一个非常真实的例子是,当一个对等点是从另一个对等点复制构造时,它需要从其源对等点访问secret信息,但同样没有理由让其他任何人知道这些内部信息
在之前的问答(HowdoIdefinefriendsinglobalnamespacewithinanotherC++namespace?)中,给出了在引用全局命名空间中的函数的命名空间中创建友元函数定义的解决方案。我对类(class)有同样的问题。classCBaseSD;namespacecb{classCBase{friendclass::CBaseSD;//m_type);};};如果我将CBaseSD放入命名空间,它就可以工作;例如。,friend类SD::CBaseSD;但我还没有找到适用于全局命名空间的咒语。我正在使用g++4.1.2进行编译。
好吧,所以我认为这是一个纯粹的C++语法问题。我有一个用ptr-to-member作为其模板参数之一定义的类:templateclassMy_list{我有另一个简单的类,它是这个类的友元。通常,我会写:classMy_friend_class{templatefriendclassMy_list;};...但是,因为第二个模板参数不是那么自由...我该如何表达友元?谢谢! 最佳答案 也许更好的问题是“为什么?”而不是“如何?”您到底想达到什么目的?当您的C++代码变得复杂和丑陋时,这通常是一个警告,表明您正在错误地处理问题。
在C++中,使类模板B的基类规范依赖于与类模板是friend的类A的私有(private)定义是否合法>B?示例代码:structEmpty{};templatestructB;structA{friendstructB;private:usingBase=Empty;};templatestructB:T::Base{};intmain(){Btest;return0;}Godbolt链接:https://godbolt.org/g/HFKaTQ代码在Clang主干(和旧版本)和MSVC19(VS2017)上编译良好,但在GCC主干(和旧版本)上编译失败:test.cpp:Inins
如此处所述C++11styleSFINAEandfunctionvisibilityontemplateinstantiation类成员函数掩盖了自由函数。使用完全限定的名称通常是可行的,但是我很难处理其他内联声明的类的友元函数。考虑以下示例:namespaceN{structC{friendintf(constC&c){return1;}friendintg(constC&c){return2;}};structD{voidf(){g(C{});//ADLfindsthis::N::f(C{});//notfounddispitefullqualification}};}我想我了解问
我有以下测试代码://friendfunction.h#includetemplateclassMyClass{templatefriendinlineconstMyClassmyFunction(constT1&x,constMyClass&y);};template::value>::type>inlineconstMyClassmyFunction(constT0&x,constMyClass&y){std::cout(y);}//friendfunction.cpp#include"friendfunction.h"intmain(intargc,char*argv[]){My
这与其说是一个实际问题,不如说是一种求知欲。我想知道在C++中是否有一种方法可以执行以下操作:让A成为一个类。我想使B类与继承自A的所有类成为friend。先说再说:我明明知道友情是不能遗传的。我想做的是制作一个templatefriend声明,也许使用SFINAE,将B与每个类C交友,以便C继承自A。这样的事情有可能吗?我试图从最简单的情况开始:你能和所有其他类(class)交friend吗?显然我知道这没有任何意义,可以将事情公开,但也许从这个起点开始可以完善事情以仅选择那些继承自A的类。 最佳答案 解决方法是使用继承的“key
我正在学习C++类中的友元函数、友元类和友元成员函数;现在,以下代码可以正常编译:#includeclassA{public:friendclassB;//friendvoidB::set(inti);//friendintB::get();friendintfunction(Aa);A(inti);voidset(inti);intget();private:inti;};A::A(inti):i(i){}voidA::set(inti){this->i=i;}intA::get(){returni;}classB{public:B(Aa);voidset(inti);intget(
声明类时A作为类(class)的friendB,而A在匿名命名空间和B中定义在外部,一些编译器会产生错误“protectedmemberinaccessible”,而其他编译器不会产生任何错误或警告。如果A或B或者两者都是模板:namespace{templatestructA{templatevoidfoo(BBconst&b){b.bar();}};}//endanonymousnamespacetemplateclassB{templatefriendstructA;protected:voidbar()const{}};intmain(){Aa;a.foo(B{});}A和B都
在阅读ThinkinginC++Volume2的“深度模板”一章时,我发现如果模板类中有一个友好的函数,则需要转发该函数的声明。我做了这个例子来测试这个,覆盖输出运算符:#includeusingnamespacestd;/*templateclassX;templateostream&operator&x);*/templateclassX{Tt;public:X(Ti):t(i){}friendostream&operator&x){returnosa(1);cout但它在没有前向声明的情况下也能工作,但后来我用类外的friendostream&operator(ostream&o