对。我错过了 - 抱歉。 - Christopher Benson-Manica |我*应该*知道我在说什么关于 - 如果我 ataru(at)cyberspace.org |不,我需要知道。欢迎火焰。 #include <vector>class Bar;class Foo{friend class Bar; /* 1 */protected:int myint;Foo() {Foo::Foo(0);}Foo( int anum ) {myint=anum;}public:int GetMyInt() {return myint;}};class Bar{protected:std::vector<Foo> vec;public:void AddAFoo( int anum ) {Foo aFoo(anum); vec.push_back(aFoo);}};int main( void ) /* just for show */{return 0;}Couple of questions:The declaration at /* 1 */ is correct, but my implementation acceptsfriend Bar;Was that syntatically legal back in the day? If not, why would myimplementation accept it?The other question is about the use of friend in general here. Theidea is that only friends of Foo should be able to instantiate it andmodify its members - is that a worthy goal, and is friend the best wayto accomplish it?--Christopher Benson-Manica | I *should* know what I''m talking about - if Iataru(at)cyberspace.org | don''t, I need to know. Flames welcome. 解决方案First of all, if only friends [and the class members] must be ableto instantiate Foo, then you better make the constructor _private_,not protected. Otherwise I can derive from Foo and instantiate allI want.Second, yes, it''s a common pattern for factory classes when they aregranted extended permissions to some class so that only they cancreate an instance of that class.VictorI like to use friends for factory classes, and not much else. It''scertainly not necessary, but it makes some things easier at times. Forexample, when you need to initialize certain members out of order, orsupply default values which cannot (easily) be done in the memberinitialization list.I''m sure there is a clever design pattern to get around this, but ...why bother? As long as you realize that friends tend to break OOPparadigms and encapsulation in general ... in the factory, though, Itend to think it actually improves encapsulation and hiding ofimplementation details, as long as only the factory gets to be afriend.--Bob Hairgrove No**********@Home.comRight. I misspoke - sorry.--Christopher Benson-Manica | I *should* know what I''m talking about - if Iataru(at)cyberspace.org | don''t, I need to know. Flames welcome. 这篇关于朋友在这里好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 13:06
查看更多