1.Josephus数小孩
#include <iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}Node,*List;
class Ring//环链表
{
private:
List First;
int Count;
int Current;
//List Begin;
public:
void Print();
void Clear(){};
void Creatlist(int n,int m,int z);
void Pivot();
};
void Ring::Creatlist(int n,int m,int z)
{
List p;
int i;
First=(Node*)malloc(sizeof(Node));
if(!First)
{
cout<<"memory allocation error!\n";
return ;
}
First->data=1; First->next=First;
for(i=n;i>1;--i)
{
p=(Node*)malloc(sizeof(Node));
if(!p)
{
cout<<"memory allocation error!\n";
return;
}
p->data=i; p->next=First->next; First->next=p;
}
Count = n;
Current = m;
if(z<1)return;
for(int j = 0;j<z;j++)
{
First=First->next;
}
}
void Ring::Print()
{
List p=First;
do
{
cout<<p->data<<" ";
p=p->next;
}while(p!=First);
cout<<endl;
}
void Ring::Pivot()
{
Node* p=First,*pre=NULL;
int i,j;
for(i=0;i<Count-1;++i)
{
for(j=1;j<Current;++j)
{
pre=p;
p=p->next;
}
cout<<"出列的人是"<<p->data<<endl;
pre->next=p->next; free(p);
p=pre->next;
}
cout<<"The winner is "<<p->data<<endl;
}
class Josephus
{
private:
int Boynumber;//孩子数量
int Beginpos;//开始位置
int Inteval;//间隔
Ring Head;
public:
void Inital();//初始化
void Getwinner();//获得胜利者
void Output();
};
void Josephus::Inital()
{
cout<<"Input the Boynumber , Inteval and Beginpos:";
cin>>Boynumber>>Inteval>>Beginpos;
if(Inteval < 2)Inteval = 2;
Head.Creatlist(Boynumber,Inteval,Beginpos);
}
void Josephus::Getwinner()
{
Head.Pivot();
}
void Josephus::Output()
{
Head.Print();
}
int main()
{
Josephus jose;
jose.Inital();
jose.Output();
jose.Getwinner();
return 0;
}
2.静态成员
#include<iostream>
using namespace std;
class Student
{
static int num;
int id;
public:
Student()
{
num++;
}
~Student()
{
num--;
}
int getid()//普通函数可以操作普通成员和静态成员,静态函数只能操作静态成员
{
id=0;
return num;
}
int getnum()
{
return num;
}
};
int Student::num=0;
int main()
{
Student t1;
Student t2;
Student *t3=new Student;
cout<<"student num1="<<t2.getnum()<<endl;
delete t3;
cout<<"student num2="<<t2.getnum()<<endl;
}
友元1(friend)
#include<iostream>
using namespace std;
class Student
{
int m_id;
public:
Student(int id)
{
m_id=id;
}
friend void test(Student t);//友元(突破封装)
};
void test(Student t)
{
cout<<"id="<<t.m_id<<endl;
}
int main()
{
Student t1(10);
test (t1);
}
友元2
#include<iostream>
using namespace std;
class Student
{
int m_id;
public:
Student(int id)
{
m_id=id;
}
friend class A;//友元(突破封装)
};
class A
{
public:
void test(Student t)
{
cout<<"id="<<t.m_id<<endl;
}
};
int main()
{
Student t1(10);
A a;
a.test (t1);
}