Welcome

首页 / 软件开发 / C++ / C++:派生类访问模板化基类(templatized base class)的命名

C++:派生类访问模板化基类(templatized base class)的命名2014-11-14派生类继承模板化基类的成员函数, 默认是无法访问, 模板化基类的命名.

原因是模板的定制化有可能取消某些函数, 为了能在编译期检测出错误, 所以默认无法访问.

派生类访问模板化基类, 包含三种方法:

1. 调用基类函数时, 使用"this->", 指明调用的类, 是本类, 在编译时, 可以进行检查;

2. 使用using声明式, 可以把基类的函数引入派生类, 在编译时, 可以进行检查;

3. 使用显示修饰(explicit qualification), 不推荐, 显示修饰会屏蔽virtual的动态绑定;

本例为: 派生类, 调用基类的函数, 重写修改格式, 进行输出;

代码:

/** test.cpp**Created on: 2014.04.18*Author: Spike*//*eclipse cdt, gcc 4.8.1*/#include <iostream>#include <string>#include <memory>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 cleartext;std::string encrypted;};template<typename Company>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<typename Company>class LoggingMsgSender : public MsgSender<Company> {public://using MsgSender<Company>::sendClear; //方法二void sendClearMsg(const MsgInfo& info) {std::cout << "Log Begin : ";//sendClear(info);this->sendClear(info); //方法一//MsgSender<Company>::sendClear(info); //方法三, 会关闭虚绑定的行为, 不建议}};int main() {MsgInfo mi = {"Clear", "Encrypted"};LoggingMsgSender<CompanyCaroline> lms;lms.sendClearMsg(mi);return 0;}
输出:

Log Begin : Cleartext: Clear
作者:csdn博客 Spike_King