zoukankan      html  css  js  c++  java
  • JZ-C-48

    剑指offer第四十八题:不能被继承的类:用C++设计一个不能被继承的类(如C#里关键字Sealed,Java里关键字final)

     1 //============================================================================
     2 // Name        : JZ-C-48.cpp
     3 // Author      : Laughing_Lz
     4 // Version     :
     5 // Copyright   : All Right Reserved
     6 // Description : 不能被继承的类:用C++设计一个不能被继承的类(如C#里关键字Sealed,Java里关键字final)
     7 //============================================================================
     8 
     9 #include <iostream>
    10 using namespace std;
    11 
    12 // ====================方法一:把构造函数设为私有函数====================
    13 class SealedClass1 {
    14 public:
    15     static SealedClass1* GetInstance() {
    16         return new SealedClass1();
    17     }
    18 
    19     static void DeleteInstance(SealedClass1* pInstance) {
    20         delete pInstance;
    21     }
    22 
    23 private:
    24     SealedClass1() {//private
    25     }
    26     ~SealedClass1() {//private
    27     }
    28 };
    29 
    30 // 如果试图从SealedClass1继承出新的类型,
    31 // 将会导致编译错误。
    32 /*
    33  class Try1 : public SealedClass1
    34  {
    35  public:
    36  Try1() {}
    37  ~Try1() {}
    38  };
    39  */
    40 
    41 // ====================方法二:利用虚拟继承virtual====================
    42 template<typename T> class MakeSealed {
    43     friend T;//友元类
    44 
    45 private:
    46     MakeSealed() {
    47     }
    48     ~MakeSealed() {
    49     }
    50 };
    51 
    52 class SealedClass2: virtual public MakeSealed<SealedClass2> {//
    53 public:
    54     SealedClass2() {
    55     }
    56     ~SealedClass2() {
    57     }
    58 };
    59 
    60 // 如果试图从SealedClass1继承出新的类型,
    61 // 将会导致编译错误。
    62 /*
    63  class Try2 : public SealedClass2
    64  {
    65  public:
    66  Try2() {}
    67  ~Try2() {}
    68  };
    69  */
    70 
    71 int main(int argc, char** argv) {
    72     return 0;
    73 }
  • 相关阅读:
    poj1580
    poj1607
    poj1313
    poj1314
    c语言之extern和static
    C笔记(一)
    搭建Linux高可用性集群(第一天)
    利用回调函数实现泛型算法
    关于SQL server中的 identity
    SQL(一)
  • 原文地址:https://www.cnblogs.com/Laughing-Lz/p/5624814.html
Copyright © 2011-2022 走看看