类成员数据的安全,主函数代码调用极其简单只有建立对象和调用对象方法的操作这两部而已,以后类一旦需要修改,只修改类体本身就可以,而主函数不需要做任何修改,这样就很好的做到了什么人做的事情什么人处理互不冲突。
程序的代码如下,我把工程文件压缩了作为此帖的附件提供下载,希望读者仔细阅读仔细推敲,真正理解面向对象oop编程的特点和意图。
主程序test4.cpp
#include <iostream> #include "josephus.h" using namespace std; void main() { Josephus a; a.initial(); cin.get(); cin.get(); } josephus.h class Josephus { public: Josephus(int num=10,int interval=1) { Josephus::num=num; Josephus::interval=interval; } void initial(); protected: int num; int interval; }; josephus.cpp #include <iostream> #include "josephus.h" #include "ring.h" using namespace std; void Josephus::initial() { int num,interval; cout<<"请输入孩子总数:"; cin>>num; if(num<2) { cout<<"孩子总数不能小于2,否则不能构成环链!"; return; } cout<<"请输入抽选号码"; cin>>interval; if(interval<1|interval>num) { cout<<"请输入抽选号码不能小于1或者大于小孩总数!"; return; } Josephus::num=num; Josephus::interval=interval; Ring a(num); a.ShowRing(num); cout<<endl; for(int i=1;i<num;i++) { a.CountInterval(interval); a.ShowWiner_loser(); a.OutChild(); } cout<<endl<<"胜利者是:"; a.ShowWiner_loser(); }
ring.h
struct Children { int number; Children *next; }; class Ring { public: Ring(int num) { josephus = new Children[num]; point = josephus; for(int i=1;i<=num;i++) { point->number = i; point->next = josephus + i % num; point=point->next; } point = &josephus[num-1]; } ~Ring() { delete[] josephus; } void ShowRing(int num); void CountInterval(int interval); void OutChild(); void ShowWiner_loser(); protected: Children *josephus; Children *point; Children *cut_point; };
ring.cpp
#include <iostream> #include "ring.h" using namespace std; void Ring::ShowRing(int num) { point=josephus;//也可以写成point=point->next;但前着效率高一点点 for(int i=1;i<=num;i++) { cout<<point->number<<","; point=point->next; } point=&josephus[num-1];//输出过后恢复point应该在的位置 } void Ring::CountInterval(int interval)//数小孩 { for(int i=0;i<interval;i++) { cut_point = point; point = cut_point->next; } } void Ring::OutChild() { cut_point->next = point->next;//将不要节点断离 point=cut_point; } void Ring::ShowWiner_loser() { cout<<point->number<<","; }
程序中需要注意的小地方是在这里
class Josephus { public: Josephus(int num=10,int interval=1) { |