zoukankan      html  css  js  c++  java
  • 石头剪子布 C++多态实现

    前几日,YX参加×公司实习笔试(http://yangxu2012.com/wordpress/?p=127),有道c++编程题,要求用Polymorphism实现石头剪子布。

    遂实现之,以期抛砖引玉。

     1 #include <iostream>
     2 #include <iomanip>
     3 #include <string>
     4 #include <stdlib.h>
     5 using namespace std;
     6 
     7 class IGuess
     8 {
     9 public:
    10     virtual string getName() = 0;
    11     virtual int getId() = 0;
    12     static char sVStable[3][3];
    13 };
    14 
    15 char IGuess::sVStable[3][3] = {'=','<','>',
    16                                '<','=','>',
    17                                '<','>','='};
    18 
    19 class Rock : public IGuess
    20 {
    21 public:
    22     string getName(){return "Rock";}
    23     int getId(){return 0;}
    24 };
    25 
    26 class Scissor : public IGuess
    27 {
    28 public:
    29     string getName(){return "Scissor";}
    30     int getId(){return 1;}
    31 };
    32 
    33 class Cloth : public IGuess
    34 {
    35 public:
    36     string getName(){return "Cloth";}
    37     int getId(){return 2;}
    38 };
    39 
    40 void VS(IGuess *a, IGuess *b)
    41 {
    42     cout << setw(10) 
    43          << a->getName()
    44          << IGuess::sVStable[a->getId()][b->getId()]
    45          << b->getName() << endl;
    46 }
    47 
    48 IGuess* randGuess()
    49 {
    50     switch( rand()%3 )
    51     {
    52     case 0:
    53         return new Rock;
    54     case 1:
    55         return new Scissor;
    56     case 2:
    57         return new Cloth;
    58     }
    59 }
    60 
    61 int main()
    62 {
    63     int i = 0;
    64     while(i++ < 10)
    65     {
    66         VS(randGuess(),randGuess());
    67     }
    68     return 0;
    69 }

    此法虽然简单粗暴,但可以忽略如何判断 石头剪子布的逻辑关系,可推广于spoke猜拳法(http://blog.sina.com.cn/s/blog_5076e00b0100q2zp.html

    附网上另外一种解法:

    (石头,剪刀,布(双分派实例))http://www.cppblog.com/mzty/archive/2007/03/22/20370.html

  • 相关阅读:
    sprintf的用法
    sscanf
    Decode the tape
    poj 1579 Function Run Fun
    Where's Waldorf?
    uva Andy's First Dictionary
    UVA Hangman Judge
    UVa Automatic Editing
    界面设计规范
    web标准下的web开发流程思考
  • 原文地址:https://www.cnblogs.com/lucantang/p/2479629.html
Copyright © 2011-2022 走看看