2014-04-24 23:28
题目:玩象棋游戏,你要设计一个bool型的方法来检测一个棋子能否移动到指定位置。
解法:不同的棋子有不同的移动规则,那么应该采取棋子基类实现接口,各个棋子子类来实现的方式。棋子除了类型之外,还必须要记录当前位置,作为判断的依据。而要移到的位置,则作为参数传给方法。不过这个题目出现在软件测试的章节里,应该是要描述如何测试吧。没学过系统的测试方法,遇到这种题的话还真没办法。
代码:
1 // 12.3 You're testing a method canMoveTo(int x, int y), which is a member method of a class Piece. Piece represents a piece in the chess game. How would you perform the testing? 2 // Answer: 3 // 1. Apparently every kind of pieces in chess has its own rule of moving. So the class Piece must be an abstract class, which will inherited by various kinds of specific pieces. 4 // 2. You always have to check if (x, y) is out of border. So this will be included in base class Piece. 5 // 3. Every piece has its own rule of moving, so the derived class will have to implement its own rule(), which will be executed by canMoveTo(). 6 // 4. The class Piece should look like this: 7 // 5. The base class will have an interface named rule(), which will be implemented by derived class. 8 class Piece { 9 public: 10 virtual bool canMoveTo(int x, int y); 11 private: 12 // ... 13 virtual bool rule(int x, int y) = 0; 14 }; 15 // 6. Thus, the test should cover two parts: 16 // 6.a. The coordinates (x, y) will cover in-bound and out-of-bound cases. 17 // 6.b. Every rule() function will be executed inside canMoveTo(), thus the test will also be included here.