zoukankan      html  css  js  c++  java
  • C++

    派生类访问模板基类(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



    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    人工神经网络(Artificial Neural Networks)
    潜语义分析(Latent Semantic Analysis)
    IOS Dictionary和Model相互转换
    jquery ajax跨域请求webservice
    日期格式转换
    1
    iptables详解
    yum报错-Network is unreachable"Error:
    41个Web开发者JavaScript实用小技巧
    比较常用的几个maven第三方镜像
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4830054.html
Copyright © 2011-2022 走看看