C++箴言:如何访问模板化基类中的名字 (3)

上一篇 / 下一篇  2008-05-04 13:52:02

已知 MsgSender 针对 CompanyZ 被特化,再次考虑 derived class(派生类)LoggingMsgSender:ITPUB个人空间/M&u XtNE n
ITPUB个人空间4H G(q.u@
template
MJ;m3N(S2l(|0class LoggingMsgSender: public MsgSender{ITPUB个人空间U$lwF%O
 public:ITPUB个人空间-n{F@ \6w J4J(g
 ...ITPUB个人空间"By)E P'|_ V:qB
 void sendClearMsg(const MsgInfo& info)
)bd/@I/CDUc0 {ITPUB个人空间A*T&|k i%s
  write "before sending" info to the log;ITPUB个人空间'Ty]6~PIgx;P
  sendClear(info); // if Company == CompanyZ,
Wk ap/s)P4B6Z0  // this function doesn't exist!ITPUB个人空间({)?4T,Cp:F
  write "after sending" info to the log;ITPUB个人空间{;_9D Q LX)o
 }ITPUB个人空间;?I/Th\A
 ...
Q ~0?2R%S{z*f E0};
ITPUB个人空间 W$qv]$hVf
  就像注释中写的,当 base class(基类)是 MsgSender时,这里的代码是无意义的,因为那个类没有提供 sendClear function(函数)。这就是为什么 C++ 拒绝这个调用:它认可 base class templates(基类模板)可以被特化,而这个特化不一定提供和 general template(通用模板)相同的 interface(接口)。结果,它通常会拒绝在 templatized base classes(模板化基类)中寻找 inherited names(继承来的名字)。在某种意义上,当我们从 Object-oriented C++ 跨越到 Template C++,inheritance(继承)会停止工作。ITPUB个人空间+t#u"n { y_*]3S+w
ITPUB个人空间] |ov;t
  为了重新启动它,我们必须以某种方式使 C++ 的 "don't look in templatized base classes"(不在模板基类中寻找)行为失效。有三种方法可以做到这一点。首先,你可以在调用 base class functions(基类函数)的前面加上 "this->":
C.N)H#mcuv:e8N0ITPUB个人空间}E kU N}'Z/p!~
template
/I"gz t,_M8|V0class LoggingMsgSender: public MsgSender{
5\_:QLl;o*IYJ%s5U N0public:
^n RF _:t#c7D0...ITPUB个人空间|1G/V9\X!vG
ITPUB个人空间H9v9R`q3^p:w W
void sendClearMsg(const MsgInfo& info)ITPUB个人空间8S`:rq(n9Kig
{ITPUB个人空间B8vHT*\u4O1ln
 write "before sending" info to the log;ITPUB个人空间 z[D+l2O4j6D e+wX
 this->sendClear(info); // okay, assumes thatITPUB个人空间#mE(Q|6F
 // sendClear will be inherited
wJ%JY,U ^3KcN0 write "after sending" info to the log;
,G7dx(m0S*G.WW0}
5v9r6{txD!N0...ITPUB个人空间 ~6{6k4|G)m
};

TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-10-11  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 53783
  • 日志数: 3708
  • 建立时间: 2008-04-12
  • 更新时间: 2008-08-15

RSS订阅

Open Toolbar