您的位置:首页 > 编程语言 > C语言/C++

C++ - 派生类访问模板基类(templatized base class)命名

2015-09-22 19:14 471 查看

派生类访问模板基类(templatized base class)命名

本文地址: http://blog.csdn.net/caroline_wendy/article/details/23993691
派生类继承模板化基类成员函数, 默认是无法訪问,
模板化基类的命名.

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

派生类訪问模板化基类, 包括三种方法:

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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: