那天写模版类时遇到了一个问题,现在记录下来备忘.
环境:Windows 2k3 sp1 + Mingw(gcc 3.4.2)
/* ========================================================================== */
/* */
/* main.c */
/* (c) 2006 ShellEx */
/* */
/* Description : 关于模版的测试 */
/* */
/* ========================================================================== */
#include
<
iostream
>
using
namespace
std;

///
//
基类
template
<
class
TElem
>
class
Base
{
public:
virtual long GetData(void){return data;};
Base(void){data = 1;};
protected:
long data;
}
;

///
//
派生类
template
<
class
TElem
>
class
Child :
public
Base
<
TElem
>
{
public:
virtual void Print(void)
{
printf("Data = %d ", data);
};
}
;

///
int
main()
{
Child <int>a;
a.Print();
printf("getData=%d", a.GetData());
return 0;
}
编译:
g++ main.cpp -o main.exe
编译提示如下错误:
main.cpp: In member function `virtual void Child<TElem>::Print()':
main.cpp:34: error: `data' undeclared (first use this function)
main.cpp:34: error: (Each undeclared identifier is reported only once for each f
unction it appears in.)
data明明是基类的成员,为何派生类Child的成员函数Print不能访问他(基类成员函数GetData是可以访问他的)?data难道不是被继承下来了么?
通过Wing老师的指点,解决方法如下:
把Print函数里的len改成this->len
原因是由于是模版,所以不确定会有多少个类似对象,编译器不知道len到底是哪种实例化对象的成员,所以用this指针就可以确保使用的是实例化后的对象,指向的是当前对象,保证唯一性.
同时感谢好友禿頭孤鳥的帮助.
环境:Windows 2k3 sp1 + Mingw(gcc 3.4.2)












































编译:
g++ main.cpp -o main.exe
编译提示如下错误:
main.cpp: In member function `virtual void Child<TElem>::Print()':
main.cpp:34: error: `data' undeclared (first use this function)
main.cpp:34: error: (Each undeclared identifier is reported only once for each f
unction it appears in.)
data明明是基类的成员,为何派生类Child的成员函数Print不能访问他(基类成员函数GetData是可以访问他的)?data难道不是被继承下来了么?
通过Wing老师的指点,解决方法如下:
把Print函数里的len改成this->len
原因是由于是模版,所以不确定会有多少个类似对象,编译器不知道len到底是哪种实例化对象的成员,所以用this指针就可以确保使用的是实例化后的对象,指向的是当前对象,保证唯一性.
同时感谢好友禿頭孤鳥的帮助.