考虑以下类:
template<typename Company>
class MsgSender
{
public:
...
void sendClear(...);
};
template<typename Company>
class LoggingMsgSender : public MsgSender<Company>
{
public:
...
void sendClearMsg(const MsgInfo & info)
{
...
sendClear(info);
...
}
};
在上面的代码中sendClear(info)
却无法通过编译。编译器会说sendClear
不存在。这是为什么?
问题在于,当编译器遭遇class template LoggingMsgSender
定义式时,并不知道它继承什么样的类.它继承的是MsgSender<Company>
,但其中的Company
是个template参数,不到后来无法知道它是什么。
无法知道是什么,就无法知道class MsgSender<Company>
看起来像什么,也就是说没法知道它是否有一个sendClear
函数.
为了解决这个问题,有三个办法:
1.在base class函数调用动作之前加上this->
:
this->sendClear(info);
2.使用using语句:
template<typename Company>
class LoggingMsgSender : public MsgSender<Company>
{
public:
using MsgSender<Company>::sendClear;
...
void sendClearMsg(const MsgInfo & info)
{
...
sendClear(info);
...
}
};
3.明白指出被调用的函数位于base class内:
...
void sendClearMsg(const MsgInfo & info)
{
...
MsgSender<Company>::sendClear(info);
...
}
...
第三种方法,有一个问题:如果被调用的是虚函数,上面的调用会关闭虚函数的绑定行为.
总结:
可在派生类模板通过this->指涉基类模板内的名称,或借由一个明白写出的基类资格修饰符完成