关于模版一个问题的测试

那天写模版类时遇到了一个问题,现在记录下来备忘.
环境: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指针就可以确保使用的是实例化后的对象,指向的是当前对象,保证唯一性.
同时感谢好友禿頭孤鳥的帮助.

 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值