作者:朱金灿
来源:http://blog.csdn.net/clever101
《MFC程序员的WTL教程》第一个例程在于说明ATL的原理,其代码如下:
#include <iostream> template<class T> class B1 { public: void SayHi() { T* pT = static_cast<T*>(this); pT->PrintClassName(); } protected: void PrintClassName() { std::wcout<<_T("This is B1")<<std::endl; } private: }; class D1:public B1<D1> { // No overridden functions at all public: protected: private: }; class D2 : public B1<D2> { public: protected: void PrintClassName() { std::wcout<<_T("This is D2")<<std::endl; } private: }; int _tmain(int argc, _TCHAR* argv[]) { D1 d1; d1.SayHi(); D2 d2; d2.SayHi(); getchar(); return 0; }
实际上这段代码是有问题。在VS 2005(带sp1)环境编译下出现以下编译错误:
d:\wtllearn\lesson1\lesson1\lesson1.cpp(14) : error C2248: 'D2::PrintClassName' :cannot access protected member declared in class 'D2'
1> d:\wtllearn\lesson1\lesson1\lesson1.cpp(38) : see declaration of 'D2::PrintClassName'
1> d:\wtllearn\lesson1\lesson1\lesson1.cpp(34) : see declaration of 'D2'
1> d:\wtllearn\lesson1\lesson1\lesson1.cpp(12) : while compiling class template memberfunction 'void B1<T>::SayHi(void)'
1> with
1> [
1> T=D2
1> ]
1> d:\wtllearn\lesson1\lesson1\lesson1.cpp(35) : see reference to class templateinstantiation 'B1<T>' being compiled
1> with
1> [
1> T=D2
1> ]
问题在于基类B1无法访问派生类D2的保护权限的成员函数。解决办法是将D2:: PrintClassName函数改为public权限。我想ATL中所有需要重载的函数应该都是public的。