假设我们要写一个应用程序,它可以把消息传送到几个不同的公司去。消息既可以以加密方式也可以以明文(不加密)的方式传送。如果我们有足够的信息在编译期间确定哪个消息将要发送给哪个公司,我们就可以用一个 template-based(模板基)来解决问题:
class CompanyA {
public:
...
void sendCleartext(const std::string& msg);
void sendEncrypted(const std::string& msg);
...
};
class CompanyB {
public:
...
void sendCleartext(const std::string& msg);
void sendEncrypted(const std::string& msg);
...
};
... // classes for other companies
class MsgInfo { ... }; // class for holding information
// used to create a message
template<typename Company>
class MsgSender {
public:
... // ctors, dtor, etc.
void sendClear(const MsgInfo& info)
{
std::string msg;
create msg from info;
Company c;
c.sendCleartext(msg);
}
void sendSecret(const MsgInfo& info) // similar to sendClear, except
{ ... } // calls c.sendEncrypted
};
这个能够很好地工作,但是假设我们有时需要在每次发送消息的时候把一些信息记录到日志中。通过一个 derived class(派生类)可以很简单地增加这个功能,下面这个似乎是一个合理的方法:
template<typename Company>
class LoggingMsgSender: public MsgSender<Company> {
public:
... // ctors, dtor, etc.
void sendClearMsg(const MsgInfo& info)
{
write "before sending" info to the log;
sendClear(info); // call base class function;
// this code will not compile!
write "after sending" info to the log;
}
...
};
注意 derived class(派生类)中的 message-sending function(消息发送函数)的名字 (sendClearMsg) 与它的 base class(基类)中的那个(在那里,它被称为 sendClear)不同。这是一个好的设计,因为它避开了 hiding inherited names(隐藏继承来的名字)的问题和重定义一个 inherited non-virtual function(继承来的非虚拟函数)的与生俱来的问题。但是上面的代码不能通过编译,至少在符合标准的编译器上不能。这样的编译器会抱怨 sendClear 不存在。我们可以看见 sendClear 就在 base class(基类)中,但编译器不会到那里去寻找它。我们有必要理解这是为什么。
