派生类继承模板化基类的成员函数, 默认是无法访问, 模板化基类的命名.
原因是模板的定制化有可能取消某些函数, 为了能在编译期检测出错误, 所以默认无法访问.
派生类访问模板化基类, 包含三种方法:
1. 调用基类函数时, 使用"this->", 指明调用的类, 是本类, 在编译时, 可以进行检查;
2. 使用using声明式, 可以把基类的函数引入派生类, 在编译时, 可以进行检查;
3. 使用显示修饰(explicit qualification), 不推荐, 显示修饰会屏蔽virtual的动态绑定;
本例为: 派生类, 调用基类的函数, 重写修改格式, 进行输出;
代码:
[cpp]
/*
* test.cpp
*
* Created on: 2014.04.18
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include
#include
#include
using namespace std;
class CompanyCaroline {
public:
void sendCleartext(const std::string& msg) {
std::cout << "Cleartext: " << msg << std::endl;
}
void sendEncrypted(const std::string& msg) {
std::cout << "Encrypted: " << msg << std::endl;
}
};
struct MsgInfo {
std::string encrypted;
};
template
class MsgSender {
public:
void sendClear(const MsgInfo& info) {
std::string msg = info.cleartext;
Company c;
c.sendCleartext(msg);
}
void sendSecret(const MsgInfo& info) {
std::string msg = info.encrypted;
Company c;
c.sendEncrypted(msg);
}
};
template
class LoggingMsgSender : public MsgSender {
public:
//using MsgSender::sendClear; //方法二
void sendClearMsg(const MsgInfo& info) {
std::cout << "Log Begin : ";
//sendClear(info);
this->sendClear(info); //方法一
//MsgSender::sendClear(info); //方法三, 会关闭虚绑定的行为, 不建议
}
};
int main() {
MsgInfo mi = {"Clear", "Encrypted"};
LoggingMsgSender lms;
lms.sendClearMsg(mi);
return 0;
}