zoukankan      html  css  js  c++  java
  • 类模板/函数模板实现父类指针指向子类对象(虚函数实现多态)

     1 // main.cpp : Defines the entry point for the console application.
     2 //
     3 
     4 #include "stdafx.h"
     5 //#include <windows.h>
     6 #include <iostream>
     7 using namespace std;
     8 
     9 
    10 template<class T>
    11 class SingletonInstance
    12 {
    13 public:
    14     static T* GetInstance()
    15     {
    16         if (nullptr == _pInstance)
    17         {
    18             _pInstance = new T();
    19             printf("instance successful!
    ");
    20         }
    21         return _pInstance;
    22     }
    23 
    24 private:
    25     SingletonInstance() :_pInstance(nullptr) {}
    26     ~SingletonInstance()
    27     {
    28         if (nullptr != _pInstance)
    29         {
    30             delete _pInstance;
    31             _pInstance = nullptr;
    32         }
    33     }
    34 
    35 private:
    36     static T* _pInstance;
    37 };
    38 
    39 template<class T>
    40 T* SingletonInstance<T>::_pInstance = NULL;
    41 
    42 
    43 
    44 template<class func>
    45 func* exchange(func param)
    46 {
    47     return &param;
    48 }
    49 
    50 
    51 class Temp
    52 {
    53 public:
    54     Temp()
    55     {
    56         /*printf("hello temp
    ");*/
    57     }
    58     virtual int linkfunction(void)
    59     {
    60         printf("hello temp
    ");
    61         return -1;
    62     }
    63 };
    64 
    65 
    66 class sonTemp: public Temp
    67 {
    68 public:
    69     int linkfunction(void) override
    70     {
    71         printf("hello son temp
    ");
    72         return 0;
    73     }
    74 };
    75 
    76 
    77 int main(int argc, _TCHAR* argv[])
    78 {
    79     // 类模板
    80     Temp *aa = SingletonInstance<sonTemp>::GetInstance();
    81     int bb = aa->linkfunction();
    82     printf("bb = %d
    ", bb);
    83 
    84 
    85 
    86     // 函数模板
    87     sonTemp *obj = new sonTemp();
    88     Temp *func = exchange(*obj);
    89     int ret = func->linkfunction();
    90     printf("ret = %d
    ", ret);
    91 
    92     return 0;
    93 }
  • 相关阅读:
    阅读《构建之法》1-5章
    构建之法第8,9,10章
    实验5-封装与测试2
    第六次作业-my Backlog
    保存内容
    实验四-单元测试
    实验3—修改版
    做汉堡-57号
    实验3-2
    201306114357-实验3-C语言
  • 原文地址:https://www.cnblogs.com/YangARTuan/p/14109782.html
Copyright © 2011-2022 走看看