首页 C++程序设计编程实例大全

C++程序设计编程实例大全

举报
开通vip

C++程序设计编程实例大全C++程序设计编程实例大全 C++程序编程实例大全 #include int main() { std::cout>name; cout>name; cout>age; cout>n; student wang; wang.no=n; cin>>wang.math; cout>n; if((p=new int[n])==0) { cout<<"can't ...

C++程序设计编程实例大全
C++程序设计编程实例大全 C++程序编程实例大全 #include int main() { std::cout<<"hello world!"; } #include "iostream" using namespace std; void main() { int *p; p=new int; *p=5; /*p=new int(5);*/ cout<<*p; delete p; } #include "iostream" using namespace std; void main() { char name[10]; cout<<"please input your name:"; cin>>name; cout<<"the name is "<>name; cout<<"how old are you:"; cin>>age; cout<<"the name is "<>n; student wang; wang.no=n; cin>>wang.math; cout<>n; if((p=new int[n])==0) { cout<<"can't allocate more memory, terminating"<>n; if((p=new int[n])==0) { cout<<"can't allocate more memory, terminating"< using namespace std; float a=2.4; void main() { int a=8; cout< void main() { int num=50; int &ref=num; ref+=10; cout<<"num="< void main() { int num; int &ref=num; num=5; cout<<"num="< //using namespace std; void main() /*{ double radius; cout<<"please input radius:"; cin>>radius; double result=radius*radius*3.14*4; cout<<"The result is "<<(double)result<<"\n"; } */ { double radius; std::cout<<"please input radius: "; std::cin>>radius; std::cout<<"The result is "< using namespace std; int array[6][4]={{60,80,90,75},{75,85,65,77},{80,88,90,98},{89,100,78,81},{62,68,69,75},{85,85,7 7,91}}; int &level(int grade[],int size,int &tA,int &tB ); void main() { int typeA=0,typeB=0; int student=6; int gradesize=4; for(int i=0;i=80) return tA; else return tB; } /* Note:Your choice is C IDE */ #include using namespace std; float &fn2(float r) { float t; t=3.14*r*r; return t; } void main() { fn2(5.0)=12.4; cout< #include using namespace std; void main() { string s,t; cout<<"please input a zifuchuan:"<>s; t="I like programming!"; cout<<"zifuchuan output:"< using namespace std; inline double circumference(double radius); void main() { double r=3.0,s; s=circumference(r); cout<<"the circumference is "< int add(int x,int y) { int sum; sum=x+y; return sum; } int add(int x,int y,int z) { int sum; sum=x+y+z; return sum; } void main() { int a,b; a=add(5,10); b=add(5,10,20); cout<<"a="< #define PI 3.1415926535 #define CS Circle_Square template double Circle_Square(T x) { return x*x*PI; } double Circle_Square(long x) { return x*x*PI; } void main() { int r1=1; double r2=2.0; long r3=3; cout<<"The first cs is "< void main() { int i=0,&l=i,&k=l; i=++l-k; cout<<"i="< class Tdate { public: void set(int,int,int); int isLeapYear(); void print(); private: int month; int day; int year; }; void Tdate::set(int m,int d,int y) { month=m;day=d;year=y; } int Tdate::isLeapYear() { return((year%4==0&&year%100!=0)||(year%400==0)); } void Tdate::print() { cout< class Tdate { public: void set(int,int,int); int isLeapYear(); void print(); private: int month; int day; int year; }; void Tdate::set(int m,int d,int y) { month=m;day=d;year=y; } int Tdate::isLeapYear() { return((year%4==0&&year%100!=0)||(year%400==0)); } void Tdate::print() { cout<print(); if((*pTdate).isLeapYear()) cout<<"error"< using namespace std; void sphere(); int main() { sphere(); } void sphere() { double radius; cout<<"please input radius:"; cin>>radius; if(radius<0) return; cout<<"the result is "< const int SIZE=10; class Cstack { private: char stk[SIZE]; int position; public: void init() { position=0; } char push(char ch); char pop(); }; char Cstack::push(char ch) { if(position==SIZE) { cout<<"栈满"<>ch; while(ch!='#'&&s.push(ch)) cin>>ch; cout< class Tdate { public: void set(int m=5,int d=16,int y=1991) { month=m;day=d;year=y; } void print() { cout< class cube { public: int volume(int ht,int wd) { return ht*wd; } int volume(int ht,int wd,int dp) { return ht*wd*dp; } private: int ht,wd,dp; }; void main() { cube c; cout< class queue {/*默认私有*/ int q[100]; int sloc,rloc; public: queue(); void qput(int i); int qget(); }; queue::queue() { sloc=rloc=0; cout<<"queue initialized"< class test { private: int num; float f1; public: test(); test(int n,float f); int getint() { return num; } float getfloat() { return f1; } }; test::test() { cout<<"Initializing default"< class Tdate { public: Tdate(int m=5,int d=16,int y=1990) { month=m;day=d;year=y; cout< #include using namespace std; class Student { public: Student(char *pName) { cout<<"call one parameter constructor"< using namespace std; class test { private: int num; float f1; public: test(); test(int n,float f); int getint() { return num; } float getfloat() { return f1; } }; test::test() { cout<<"Initializing default"< using namespace std; class test { private: int num; float f1; public: test(int n); test(int n,float f); }; inline test::test(int n) { cout<<"Initializing\t"< using namespace std; class test { private: int num; float f1; public: test(int n); test(int n,float f); }; inline test::test(int n) { cout<<"Initializing\t"< using namespace std; int main() { for(int i=1;i<=10;i++) { for(int j=1;j<=i;++j) cout<<"M"; cout< class Tdate{ public: Tdate(int m=5,int d=16,int y=1990) { month=m;day=d;year=y; cout< #include using namespace std; void main() { try { exception theError; throw(theError); } catch(const exception &theError) { cout< #include using namespace std; class Person { public: Person(char *na) { cout<<"call constructor"< using namespace std; class SillyClass { public: SillyClass(int&i):ten(10),refI(i) {} protected: const int ten; int&refI; }; void main() { int i; SillyClass sc(i); cout< class RMB { public: RMB(double value=0.0); operator double() {return yuan+jf/100.0;} void display() { cout<<(yuan+jf/100.0)< #include class Student { public: Student(char *pName="no name",int ssId=0) { strncpy(name,pName,40); name[39]='\0'; id=ssId; cout<<"Constructing new student"< #include using namespace std; void main() { try { exception theError; throw(theError); } catch(const exception &theError) { cout< class Student { public: Student() { cout<<"constructing student.\n"; semesHours=100; gpa=3.5; } ~Student() {cout<<"destructing student.\n";} protected: int semesHours; float gpa; }; class Teacher { public: Teacher() {cout<<"constructing teacher.\n";} ~Teacher() {cout<<"destructing teacher.\n";} }; class Tutorpair { public: Tutorpair() { cout<<"constructing tutorpair.\n"; nomeeting=0; } ~Tutorpair() { cout<<"destructing tutorpair.\n"; } protected: Student student; Teacher teacher; int nomeeting; }; void main() { Tutorpair tp; cout<<"back main.\n"; } #include class A { static int i; public: A() { i++; } int list() {return i;} }; int A::i=0; void main() { A a1,a2,a3; cout< #include class Student { public: Student(char *pName="no name") { cout<<"create one student\n"; strncpy(name,pName,40); name[39]='\0'; noOfStudents++; cout< using namespace std; int main() { for(int i=1;i<=10;++i) { for(int j=1;j<=i-1;++j) cout<<" "; for(int k=1;k<=21-2*i;++k) cout<<"M"; cout< #include class Student { public: Student(char *pName); ~Student(); protected: static Student *pFirst; Student *pNext; char name[40]; }; Student * Student::pFirst=0; Student::Student(char *pName) { strncpy(name,pName,sizeof(name)); name[sizeof(name)-1]='\0'; pNext=pFirst; pFirst=this; } Student::~Student() { cout<name<pNext) if(pS->pNext==this) { pS->pNext=pNext; return; } } Student *fn() { Student *pS=new Student("Jenny"); Student sb("Jone"); return pS; } void main() { Student sa("Jamsa"); Student *sb=fn(); Student sc("Tracey"); delete sb; } #include #include class string { static int total_length; int length; char * contents; public: string(char *s) { length=strlen(s); contents=new char[length +1]; strcpy(contents,s); } static int set_total_length(string&obj) { total_length+=obj.length; return total_length; } ~string() {delete[]contents;} }; int string::total_length=0; void main() { string obj1("the first object"); cout< class A { public: int i,*p; A(){i=10;p=&i;} }; int A::*p=&A::i; void main() { A aa,bb; (bb.*p)++; -- *aa.p; cout<<"AA:"< class A { int i; public: int set(int k) { i=++k;return i; } }; void main() { int(A::*f)(int)=&A::set; A aa; cout<<(aa.*f)(10)< class A { static int i; friend class B; public: static void set(int k) {i=k;i++;} }; class B { public: static void ds(int l) { int *p=&A::i; cout<<*p<<"\n"; *p=1;cout<<*p; } }; int A::i=0; void(*f1)(int)=&A::set; void(*f2)(int)=&B::ds; void main() { f1(10); f2(20); } #include const maxCard=16; enum ErrCode{noErr,overflow}; enum Bool{False,True}; class Set { int elems[maxCard]; int card; public: void EmptySet(){card=0;} Bool Member(int); ErrCode AddElem(int); void RmvElem(int); void Copy(Set *); Bool Equal(Set *); void Print(); void Intersect(Set *,Set *); ErrCode Union(Set *,Set *); }; Bool Set::Member(int elem) { for(int i=0;ielems[i]=elems[i]; set->card=card; } Bool Set::Equal(Set *set) { if(card!=set->card) return False; for(int i=0;iMember(elems[i])) return False; return True; } void Set::Print() { cout<<"{"; for(int i=0;i*res { res->card=0; for(int i=0;icard;++j) if(elems[i]==set->elems[j]) { res->elems[res->card++]=elems[i]; break; } } ErrCode Set::Union(Set *set,Set *res) { set->Copy(res); for(int i=0;iAddElem(elems[i])==overflow) return overflow; return noErr; } void main() { Set s1,s2,s3; s1.EmptySet(); s2.EmptySet(); s3.EmptySet(); s1.AddElem(10); s1.AddElem(20); s1.AddElem(30); s1.AddElem(40); s2.AddElem(30); s2.AddElem(50); s2.AddElem(10); s2.AddElem(60); cout<<"s1=";s1.Print(); cout<<"s2=";s2.Print(); s2.RmvElem(50); cout<<"s2-{50}";s2.Print(); if(s1.Member(20)) cout<<"20 is in s1\n"; s1.Intersect(&s2,&s3); cout<<"s1 intsec s2=";s3.Print(); s1.Union(&s2,&s3); cout<<"s1 union s2";s3.Print(); if(!s1.Equal(&s2)) cout<<"s1!=s2\n"; } #include const maxCard=16; enum ErrCode{noErr,overflow}; enum Bool {False,True}; class Set { int size; int *elems; int card; public: Set(int sz=maxCard) {card=0;size=sz;elems=new int[size];} ~Set(){delete []elems;} Bool Member(int); ErrCode AddElem(int); void RmvElem(int); void Copy(Set *); Bool Equal(Set *); void Print(); void Intersect(Set *,Set *); ErrCode Union(Set *,Set *); }; Bool Set::Member(int elem) { for(int i=0;isizeelems; set->elems=new int[size]; set->size=size; } for(int i=0;ielems[i]=elems[i]; set->card=card; } Bool Set::Equal(Set *set) { if(card!=set->card) return False; for(int i=0;iMember(elems[i])) return False; return True; } void Set::Print() { cout<<"{"; for(int i=0;i0) cout<sizeelems; res->elems=new int[size]; res->size=size; } res->card=0; for(int i=0;icard;++j) if(elems[i]==set->elems[j]) { res->elems[res->card++]=elems[i]; break; } } ErrCode Set::Union(Set *set,Set *res) { if(res->sizesize) { delete []res->elems; res->elems=new int[size+set->size]; res->size=size+set->size; } set->Copy(res); for(int i=0;iAddElem(elems[i])==overflow) return overflow; return noErr; } void main() { Set s1,s2,s3; s1.AddElem(10); s1.AddElem(20); s1.AddElem(30); s1.AddElem(40); s2.AddElem(30); s2.AddElem(50); s2.AddElem(10); s2.AddElem(60); cout<<"s1=";s1.Print(); cout<<"s2=";s2.Print(); s2.RmvElem(50); cout<<"s2-{50}=";s2.Print(); if(s1.Member(20)) cout<<"20 is in s1\n"; s1.Intersect(&s2,&s3); cout<<"s1 intsec s2=";s3.Print(); s1.Union(&s2,&s3); cout<<"s1 union s2=";s3.Print(); if(!s1.Equal(&s2)) cout<<"s1!=s2\n"; } #include class Tx { public: Tx(int i,int j); ~Tx(); void display(); private: int num1,num2; }; Tx::Tx(int i,int j=10) { num1=i; num2=j; cout<<"Constructing"< #include class Student { char name[10],num[10]; public: Student(char *s1,char *s2) { strcpy(name,s1); strcpy(num,s2); } void dsp() { cout<<"Name:"< #include using namespace std; int main() { cout<<"please input a number:\n"; int m; cin>>m; double sqrtm=sqrt(m*1.0); for(int i=2;i<=sqrtm;++i) if(m%i==0) { cout< #include class Student { private: char name[10],num[10]; friend void show(Student&st) { cout<<"Name:"<mat<<"\nPhysics:"<phy<<"\nEnglish:"<eng< #include class myclass { int x,y; char *string; public: myclass(int vx,int vy,char *str); friend int sum(myclass c1); friend int strlength(myclass c1); friend void print(myclass c1); }; myclass::myclass(int vx,int vy,char *str) { x=vx; y=vy; string=new char[strmax]; strcpy(string,str); } int sum(myclass c1) {return c1.x+c1.y;} int strlength(myclass c1) {return strlen(c1.string);} void print(myclass c1) { cout<<"x="< using namespace std; int main() { for(int i=1;i<=10;++i) { for(int j=1;j<=10-i;++j) cout<<" "; for(char ch='A';ch<'A'+2*i-1;++ch) cout< using namespace std; int main() { cout<<"please input a number:\n"; int m; cin>>m; for(int i=2;i #include class myclass { int x,y; char *string; public: myclass(int vx,int vy,char *str); friend int sum(myclass c1); friend int strlength(myclass c1); friend void print(myclass c1); }; myclass::myclass(int vx,int vy,char *str) { x=vx; y=vy; string=new char[strmax]; strcpy(string,str); } int sum(myclass c1) { return (c1.x+c1.y); } int strlength(myclass c1) { return strlen(c1.string); } void print(myclass c1) { cout<<"x="< class realset; enum errcode{noerr,overflow}; class intset { int elem[maxcard]; int card; public: intset() {card=0;} errcode addelem(int); void print(); void settoreal(realset *set); }; class realset { float elem[maxcard]; int card; public: realset() {card=0;} errcode addelem(float); void print(); }; errcode intset::addelem(int elem1) { for(int i=0;i0) cout<addelem((float)elem[i]); } errcode realset::addelem(float elem1) { for(int i=0;i0) cout<print(); delete set2; } #include #include class Student; class Score { unsigned int mat,phy,eng; public: Score(unsigned int i1,unsigned int i2,unsigned int i3):mat(i1),phy(i2),eng(i3){} void show() { cout<<"Mathematics:"< #include class Student { friend class Score; char name[10],num[10]; public: Student(char *s1,char *s2) {strcpy(name,s1);strcpy(num,s2);} }; class Score { unsigned int mat,phy,eng; public: Score(unsigned int i1,unsigned int i2,unsigned int i3):mat(i1),phy(i2),eng(i3){} void show() {cout<<"Mathematics:"< class stack; class node { int data; node *prev; public: node(int d,node *n) { data=d; prev=n; } friend class stack; }; class stack { node *top; public: stack() { top=0; } void push(int i); int pop(); }; void stack::push(int i) { node *n=new node(i,top); top=n; } int stack::pop() { node *t=top; if(top) { top=top->prev; int c=t->data; delete t; return c; } return 0; } void main() { int c; stack s; for(int i=0;i<10;i++) { cin>>c; s.push(c); } for(i=0;i<10;i++) cout< class Complex { double real; double image; public: Complex(double r=0, double i=0) { real=r; image=i; } friend void inputcomplex(Complex &comp); friend Complex addcomplex(Complex &c1,Complex &c2); friend Complex subcomplex(Complex &c1,Complex &c2); friend Complex mulcomplex(Complex &c1,Complex &c2); friend void outputcomplex(Complex &comp); }; void inputcomplex(Complex &comp) { cin>>comp.real>>comp.image; } Complex addcomplex(Complex &c1,Complex &c2) { Complex c; c.real=c1.real+c2.real; c.image=c1.image+c2.image; return c; } Complex subcomplex(Complex &c1,Complex &c2) { Complex c; c.real=c1.real-c2.real; c.image=c1.image-c2.image; return c; } Complex mulcomplex(Complex &c1,Complex &c2) { Complex c; c.real=c1.real*c2.real-c1.image*c2.image; c.image=c1.real*c2.image+c1.image*c2.real; return c; } void outputcomplex(Complex &comp) { cout<<"("< class vehicle { private: int wheels; float weight; public: vehicle(int in_wheels,float in_weight) {wheels=in_wheels;weight=in_weight;} int get_wheels(){return wheels;} float get_weight(){return weight;} }; class car:private vehicle { private: int passenger_load; public: car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight){passenger_load=people;} int get_wheels(){return vehicle::get_wheels();} float get_weight(){return vehicle::get_weight();} int get_passengers(){return passenger_load;} }; void main() { car bm(4,1000); cout<<"The message of bm(wheels,weight,passengers):"< class vehicle { private: int wheels; protected: float weight; public: vehicle(int in_wheels,float in_weight) {wheels=in_wheels;weight=in_weight;} int get_wheels() {return wheels;} float get_weight() {return weight;} }; class car:protected vehicle { private: int passenger_load; public: car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight){passenger_load=people;} int get_wheels(){return vehicle::get_wheels();} float get_weight(){return weight;} int get_passengers(){return passenger_load;} }; void main() { car bm(4,1000); cout<<"The message of bm(wheels,weight,passengers):"< class data { int x; public: data(int x) { data::x=x; cout<<"class data\n"; } }; class a { data d1; public: a(int x):d1(x) {cout<<"class a\n";} }; class b:public a { data d2; public: b(int x):a(x),d2(x) {cout<<"class b\n";} }; class c:public b { public: c(int x):b(x) {cout<<"class c\n";} }; void main() { c object(5); } #include #include class ST_COM { protected: char name[10]; unsigned int num; float mat,eng,phy; public: ST_COM(char *na,unsigned int n,float ma,float en,float ph):num(n),mat(ma),eng(en),phy(ph) {strcpy(name,na);} }; class EL_DEP:public ST_COM { float pex,elnet,dst; public: EL_DEP(char *na,unsigned int n,float ma,float en,float ph,float pe,float el,float d):ST_COM(na,n,ma,en,ph),pex(pe),elnet(el),dst(d){} void operator!() { cout<<"Name:"< #include class ST_COM { protected: char name[10]; unsigned int num; float mat,eng,phy,avg; public: ST_COM(char *na,unsigned int n,float ma,float en,float ph):num(n),mat(ma),eng(en),phy(ph) { strcpy(name,na); avg=(mat+eng+phy)/3; } void operator!() { cout<<"Name:"< class person { char *name; int age; char add; public: person() {cout<<"the constructor of class persons!\n";} ~person() {cout<<"the adestructor of class persons!\n";} }; class student:public person { char *department; int level; public: student() {cout<<"the constructor of class student!\n";} ~student() {cout<<"the adestructor of class student!\n";} }; class teacher:public person { char *major; float salary; public: teacher() {cout<<"the constructor of class teacher!\n";} ~teacher() {cout<<"the adestructor of class teacher!\n";} }; void main() { student d1; teacher d2; } #include class Bed { public: Bed():weight(){} void Sleep(){cout<<"Sleeping...\n";} void SetWeight(int i){weight=i;} protected: int weight; }; class Sofa { public: Sofa():weight(){} void WatchTV(){cout<<"Watching TV\n";} void SetWeight(int i){weight=i+2;} protected: int weight; }; class SleeperSofa:public Bed,public Sofa { public: SleeperSofa(){} void FoldOut(){cout<<"Fold out the sofa.\n";} }; void main() { SleeperSofa ss; ss.WatchTV(); ss.Sleep(); ss.Bed::SetWeight(20); ss.Sofa::SetWeight(20); } #include class Furniture { public: Furniture(){} void SetWeight(int i){weight=i;} int GetWeight(){return weight;} protected: int weight; }; class Bed:virtual public Furniture { public: Bed(){} void Sleep(){cout<<"Sleeping...\n";} }; class Sofa:virtual public Furniture { public: Sofa(){} void WatchTV(){cout<<"Watching TV...\n";} }; class SleeperSofa:public Bed,public Sofa { public: SleeperSofa():Sofa(),Bed(){} void FoldOut(){cout<<"Fold out the sofa.\n";} }; void main() { SleeperSofa ss; ss.SetWeight(20); cout< class base { public: base(){cout<<"this is base class!\n";} }; class base2 { public: base2(){cout<<"this is base2 class!\n";} }; class level1:public base2,virtual public base { public: level1(){cout<<"this is level1 class!\n";} }; class level2:public base2,virtual public base { public: level2(){cout<<"this is level2 class!\n";} }; class toplevel:public level1,virtual public level2 { public: toplevel(){cout<<"this is toplevel class!\n";} }; void main() { toplevel topobj; } #include class OBJ1 { public: OBJ1(){cout<<"OBJ1\n";} ~OBJ1(){cout<<"destructing OBJ1"< template class tem { T *data; int size; public : tem(int); ~tem() {delete[] data;} T& operator[](int i) {return data[i];} }; template tem::tem(int n) { data=new T[n]; size=n; } void main() { tem x(5); int i; for(i=0;i<5;i++) x[i]=i; for(i=0;i<5;i++) cout< #include class Person { protected: char m_strName[10]; int m_nSex; int m_nAge; public: Person(char *name,int age,char sex) { strcpy(m_strName,name); m_nSex=(sex=='m'?0:1); m_nAge=age; } void ShowMe() { cout<<"姓名:"< #include template class List { public: List(); void Add(T&); void Remove(T&); T *Find(T&); void PrintList(); ~List(); protected: struct Node { Node *pNext; T *Pt; }; Node *pFirst; }; template List::List() { pFirst=0; } template void List::Add(T& t) { Node *temp=new Node; temp->Pt=&t; temp->pNext=pFirst; pFirst=temp; } template void List::Remove(T& t) { Node *q=0; if(*pFirst->Pt==t) { q=pFirst; pFirst=pFirst->pNext; } else { for(Node *p=pFirst;p->pNext;p=p->pNext) if(*(p->pNext->Pt)==t) { q=p->pNext; p->pNext=q->pNext; break; } } if(q) { delete q->Pt; delete q; } else cout<<"No such node!"< T* List::Find(T& t) { for(Node *p=pFirst;p;p=p->pNext) { if(*(p->Pt)==t) return p->Pt; } return 0; } template void List::PrintList() { for(Node *p=pFirst;p;p=p->pNext) { cout<<*(p->Pt)<<"|"; } cout< List::~List() { Node *p=pFirst; while(!p) { pFirst=pFirst->pNext; delete p->Pt; delete p; p=pFirst; } } void main() { List floatList; for(int i=1;i<7;i++) { floatList.Add(* new float((float)(i+0.3))); } floatList.PrintList(); float b=(float)3.3; float *pa=floatList.Find(b); if(pa) floatList.Remove(*pa); floatList.Remove(*new float((float)0.3)); floatList.PrintList(); } #include #include class employee { protected: char name[10]; char emp_id[8]; double salary; public: void setinfo(char *empname,int empsex,char *empid) { strcpy(name,empname); strcpy(emp_id,empid); } void getinfo(char *empname,char *empid) { strcpy(empname,name); strcpy(empid,emp_id); } double getsalary() { return salary; } }; class hourlyworker:public employee { protected: int hours; double perhourpay; public: hourlyworker() { hours=0; perhourpay=15.6; } int gethours() { return hours; } void sethours(int h) { hours=h; } double getperhourpay() { return perhourpay; } void setperhourpay(double pay) { perhourpay=pay; } void computepay() { if(hours<=40) salary=perhourpay*hours; else salary=perhourpay*40+(hours-40)*1.5*perhourpay; } }; class pieceworker:public employee { protected: int pieces; double perpiecepay; public: pieceworker() { pieces=0; perpiecepay=26.8; } int getpieces() { return pieces; } void setpieces(int p) { pieces=p; } double getperpiecepay() { return perpiecepay; } void setperpiecepay(double ppp) { perpiecepay=ppp; } void computepay() { salary=pieces*perpiecepay; } }; class manager:public employee { public: void setsalary(double s) { salary=s; } }; class commissionworker:public employee { protected: double basesalary; double total; double percent; public: commissionworker() { basesalary=500; total=0; percent=0.01; } double getbase() { return basesalary; } void setbase(double base) { basesalary=base; } double gettotal() { return total; } void settotal(double t) { total=t; } double getpercent() { return percent; } double setpercent(double p) { percent=p; } void computepay() { salary=basesalary+total*percent; } }; void main() { char name[10],emp_id[9]; hourlyworker hworker; hworker.setinfo("John",0,"001"); hworker.sethours(65); hworker.getinfo(name,emp_id); hworker.computepay(); cout<<"hourlyworker "< #include template class BinaryTree; template class Node { Node *lchild,*rchild; T info; public: Node() { lchild=NULL; rchild=NULL; } Node(T data,Node *left=NULL,Node *right=NULL) { info=data; lchild=left; rchild=right; } friend class BinaryTree; }; template class BinaryTree { Node *root; void InOrder(Node *Current); void Insert(const T &data,Node * &b); void Remove(const T &data,Node * &a,Node * &b); void Destory(Node *Current); public: BinaryTree() { root=NULL; } ~BinaryTree() { Destory(root); } void Creat(T *data,int n); void InOrder() { InOrder(root); } void Remove(const T &data) { Remove(data,root,root); } }; template void BinaryTree::Destory(Node *Current) { if(Current!=NULL) { Destory(Current->lchild); Destory(Current->rchild); delete Current; } } template void BinaryTree::Insert(const T &data,Node * &b) { if(b==NULL) { b=new Node(data); if(b==NULL) { cout<<"空间不足"<info) Insert(data,b->lchild); else Insert(data,b->rchild); } template void BinaryTree::Creat(T *data,int n) { for(int i=0;i void BinaryTree::InOrder(Node *Current) { if(Current!=NULL) { InOrder(Current->lchild); cout<info<<" "; InOrder(Current->rchild); } } template void BinaryTree::Remove(const T &data,Node * &a,Node * &b) { Node *temp1,*temp2; if(b!=NULL) if(datainfo) Remove(data,b,b->lchild); else if(data>b->info) Remove(data,b,b->rchild); else if(b->lchild!=NULL&&b->rchild!=NULL) { temp2=b; temp1=b->rchild; if(temp1->lchild!=NULL) { while(temp1->lchild!=NULL) { temp2=temp1; temp1=temp1->lchild; } temp2->lchild=temp1->rchild; } else temp2->rchild=temp1->rchild; b->info=temp1->info; delete temp1; } else { temp1=b; if(b->rchild!=NULL) { temp1=b->rchild; b->info=temp1->info; b->rchild=temp1->rchild; b->lchild=temp1->lchild; } else if(b->lchild!=NULL) { temp1=b->lchild; b->info=temp1->info; b->rchild=temp1->rchild; b->lchild=temp1->lchild; } else if(b==root) root=NULL; else if(a->rchild==temp1) a->rchild=NULL; else a->lchild=NULL; delete temp1; } } void main() { const int n=15; int i,a[n]={10,5,15,8,3,18,13,12,14,16,20,1,4,6,9}; BinaryTree btree; btree.Creat(a,n); cout<<"输入数据:"< btree1; btree1.Creat(a1,1); cout<<"输入数据:"<<"\t"< class RMB { public: RMB(unsigned int d,unsigned int c); RMB operator +(RMB&); RMB& operator ++(); void display() { cout<<(yuan+jf/100.0)<=100) { yuan++; jf-=100; } } RMB RMB::operator +(RMB& s) { unsigned int c=jf+s.jf; unsigned int d=yuan+s.yuan; RMB result(d,c); return result; } RMB& RMB::operator ++() { jf++; if(jf>=100) { jf-=100; yuan++; } return *this; } void main() { RMB d1(1,60); RMB d2(2,50); RMB d3(0,0); d3=d1+d2; ++d3; d3.display(); } #include #include class String { char name[256]; public: String(char *str) { strcpy(name,str); } String() {} String operator +(const String&); void display() { cout<<"The string is:"< #include class String { char name[256]; public: String(char *str) { cout<<"constructor,char *---->String\n"; strcpy(name,str); } String(String &s) { cout<<"copy constructor\n"; strcpy(name,s.name); } String() {cout<<"default constructor\n";} ~String() {} String operator +(const String&); void operator =(const String& s) { strcpy(name,s.name); cout<<"operator ="< class RMB { public: RMB(unsigned int d,unsigned int c); friend RMB operator +(RMB&,RMB&); friend RMB& operator ++(RMB&); void display() { cout<<(yuan+jf/100.0)<=100) { yuan++; jf-=100; } } RMB operator +(RMB& s1,RMB& s2) { unsigned int jf=s1.jf+s2.jf; unsigned int yuan=s1.yuan+s2.yuan; RMB result(yuan,jf); return result; } RMB& operator ++(RMB& s) { s.jf++; if(s.jf>=100) { s.jf-=100; s.yuan++; } return s; } void main() { RMB d1(1,60); RMB d2(2,50); RMB d3(0,0); d3=d1+d2; ++d3; d3.display(); } #include #include class String { char name[256]; public: String(char *str) { strcpy(name,str); } String() {} ~String() {} friend String operator +(const String&,const String&); void display() { cout<<"The string is:"< class complex { float real,imag; public: complex(float r=0,float i=0) { real=r; imag=i; } void print(); friend complex operator +(complex a,complex b); friend complex operator -(complex a,complex b); friend complex operator *(complex a,complex b); friend complex operator /(complex a,complex b); }; void complex::print() { cout<0) cout<<"+"; if(imag!=0) cout< #include class Student { char name[10]; float score[3]; static unsigned int sum; public: void operator [](Student&); Student(char *na,float ma=0,float en=0,float ph=0) { score[0]=ma;score[1]=en;score[2]=ph;strcpy(name,na); } void operator !() { if(sum>0) cout<<"Mat:"< class Increase { public: Increase(int x):value(x){} Increase & operator ++(); Increase operator ++(int); void display() { cout<<"the value is:"< class Increase { public: Increase(int x):value(x){} friend Increase & operator ++(Increase&); friend Increase operator ++(Increase&,int); void display() { cout<<"the value is:"< class pp { public: int n; float m; pp * operator->() { return this; } }; void main() { pp t1; t1->m=10; cout<<"t1. m is:"<m is:"<m< class Sample { int n; public: Sample() {} Sample(int i) { n=i; } Sample & operator =(Sample); void disp() { cout<<"n="< #include using namespace std; class Person { public: Person(char *na) { cout<<"call constructor"< #include class Name { public: Name() {pName=0;} Name(char *pn) {copyName(pn);} ~Name() {deleteName();} Name & operator =(Name& s) { deleteName(); copyName(s.pName); return *this; } void display() {cout< #include class Point { int x,y; public: Point() {} Point(int l,int w) { x=l; y=w; } void disp() { cout<<"面积:"< class base { public: void who() { cout<<"this is the class of base !"<who(); p=&obj2; p->who(); ((derive2 *)p)->who(); obj2.who(); obj3.who(); } #include class base { public: virtual void f1() { cout<<"f1 function of base"<f1(); ptr->f2(); ptr->f3(); ptr=&obj2; ptr->f1(); ptr->f2(); ptr->f3(); } #include class A { public: A() { cout<<"the constructor of class is A"<f(); p->g(); p->h(); a.f(); a.g(); a.h(); b.f(); b.g(); b.h(); } #include class base { public: base(){} virtual void vf() { cout<<"base::vf() called"< class base { public: virtual void print() { cout<<"class base\n"; } }; class son:public base { public: virtual void print(){} }; class grandson:public son { public: virtual void print() { cout<<"class grandson!\n"; } }; void show(base *p) { p->print(); } void main() { base *pbase=new base; son *pson=new son; grandson *pgrandson=new grandson; show(pbase); show(pson); show(pgrandson); } #include class shape { public: virtual float area()=0; }; class triangle:public shape { protected: float h,w; public: triangle(float hh,float ww) { h=hh; w=ww; } float area() {return float(h*w*0.5);} }; class rectangle:public triangle { public: rectangle(float h,float w):triangle(h,w){} float area() {return h*w;} }; class circle:public shape { private: float radius; public: circle(float r) {radius=r;} float area() { return float(radius*radius*3.14); } }; float total(shape *s[],int n) { float sum=0; for(int j=0;jarea(); return sum; } void main() { shape *s[4]; s[0]=new triangle(3,4); s[1]=new rectangle(2,4); s[2]=new circle(5); s[3]=new circle(8); float sum=total(s,4); cout< #include #include class person { friend class list; protected: char name[20]; int age; char add[40]; char tele[15]; static person *ptr; person *next; public: person(char *,int,char *,char *); virtual void print(); virtual void insert()=0; }; class student:public person { friend class list; int level; float grade_point_average; public: student(char *,int,char *,char *,int,float ); void print(); void insert(); }; class teacher:public person { friend class list; float salary; public: teacher(char *,int,char *,char *,float ); void print(); void insert(); }; class staff:public person { friend class list; float hourly_wages; public: staff(char *,int,char *,char *,float ); void print(); void insert(); }; class list { person *root; public: list() {root=0;} void insert_person(person *node); void remove(char *name); void print_list(); }; person::person(char *name,int age,char *add,char *tele) { strcpy(person::name,name); strcpy(person::add,add); strcpy(person::tele,tele); person::age=age; next=0; } void person::print() { cout<<"\nname:"<name); person *curr_node=root; person *previous=0; while(curr_node!=0&&strcmp(curr_node->name,key)<0) { previous=curr_node; curr_node=curr_node->next; } node->insert(); node->ptr->next=curr_node; if(previous==0) root=node->ptr; else previous->next=node->ptr; } void list::remove(char *name) { person *curr_node=root; person *previous=0; while(curr_node!=0&&strcmp(curr_node->name,name)!=0) { previous=curr_node; curr_node=curr_node->next; } if(curr_node!=0&&previous==0) { root=curr_node->next; delete curr_node; } else if(curr_node!=0&&previous!=0) { previous->next=curr_node->next; delete curr_node; } } void list::print_list() { person *cur=root; while(cur!=0) { cur->print(); cur=cur->next; } } person *person::ptr=0; void main() { list people; student stu("wangchong",20,"shanghai","024578414",3,54); teacher tea("lining",43,"beijing","011645274",564); staff sta("chenling",42,"qingdao","213456715",20); people.insert_person(&stu); people.insert_person(&tea); people.insert_person(&sta); people.print_list(); cout< #include class base { char *p; public: base(int sz,char *bptr) { p=new char [sz]; strcpy(p,bptr); cout<<"constructor base"< #include class fairy_tale { public: virtual void act1() { cout<<"princess meets frog\n"; act2(); } void act2() { cout<<"princess kisses frog\n"; act3(); } virtual void act3() { cout<<"frog turns into prince\n"; act4(); } virtual void act4() { cout<<"they live happy ever after\n"; act5(); } virtual void act5() { cout<<"the end\n"; } }; class unhappy_tale:public fairy_tale { void act3() { cout<<"frog stays another frog\n"; act4(); } void act4() { cout<<"princess runs away in disgust\n"; act5(); } void act5() { cout<<"the not-so-happy end\n"; } }; void main() { char ch; fairy_tale *tale; cout<<"which tale would you like to hear(f/u)?\n"; cin>>ch; if(ch=='f') tale=new fairy_tale; else tale=new unhappy_tale; tale->act1(); delete tale; } #include #include void main() { int x=30,y=300,z=1024; cout<<"Decimal:"< #include void main() { int x=30,y=300,z=1024; cout<<"Decimal:"< #include void main() { int a=10; int b=1000; cout< #include void main() { /*cout< #include void main() { double test=22.0/7; cout< #include void main() { cout< #include void main() { double x=66,y=-8.246; cout< #include void main() { double x=66,y=-8.246; cout< void main() { char str[250]; cout<<"请输入一个字符串:\n"; cin.getline(str,sizeof(str),','); cout<<"输入的字符串为:"< void main() { int x=123; double y=-33.1415926; cout<<"x="; cout.width(10); cout< class complex { float real,image; public: complex(float r=0,float i=0) { real=r; image=i; } friend ostream & operator <<(ostream &,complex &); friend istream & operator >>(istream &,complex &); }; ostream & operator <<(ostream &output,complex &obj) { output<0) output<<"+"; if(obj.image!=0) output<>(istream &input,complex &obj) { cout<<"Input the real,image of the complex\n"; input>>obj.real; input>>obj.image; return input; } void main() { complex c1(2.3,4.6),c2(3.6,2.8),c3; cout<<"the value of c1 is:"<>c3; cout<<"the value of c3 is:"< #include #include void main() { ofstream myf("e:\\myabc.txt"); char txt[255]; while(1) { cin.getline(txt,255); if(strlen(txt)==0) break; myf< #include class student { public: char name[10]; int num; int age; char addr[15]; friend ostream & operator <<(ostream &out,student &s); friend istream & operator <<(istream &in,student &s); }; ostream & operator <<(ostream &out,student &s) { out<>(istream &in,student &s) { in>>s.name>>s.num>>s.age>>s.addr; return in; } void main() { ofstream ofile; ifstream ifile; ofile.open("e:\\s.txt"); student s; for(int i=1;i<=3;i++) { cout<<"请输入第"<>s; ofile<>s; while(!ifile.eof()) { cout<>s; } ifile.close(); } #include #include void main() { int n,i,flag,count=0; for(n=2;n<=100;n++) { flag=1; for(i=2;i<=sqrt(n);i++) if(n%i==0) { flag=0; break; } if(flag==1) { cout< #include void main() { int n,i,count=0; for(n=2;n<=100;n++) { for(i=2;i<=sqrt(n);i++) if(n%i==0) { break; } else { cout< int fact(int n) { long int f; if(n==0||n==1) f=1; else f=fact(n-1)*n; return f; } void main() { long int t=0; for(int i=1;i<=20;i++) t+= fact(i); cout< void main() { double sum=0,t=1,i,j; for(i=1;i<=20;i++) { /*for(j=1;j<=i;j++) */ t=t*j; sum+=t; } cout< void main() { int sum=0,t=1,i,j; for(i=1;i<=5;i++) { t*=i; sum+=t; } cout< #include #include #include #include void sort(int [],int); void main() { fstream dat,out; int i,a[20],b[20]; dat.open("E:\\file.dat",ios::binary|ios::out|ios::in); if(!dat) { cout<<"can't open file\n"; exit(0); } for(i=0;i<20;i++) { a[i]=rand(); dat.write((char *)&a[i],sizeof(int)); } dat.seekg(0); for(i=0;i<20;i++) { dat.read((char *)&b[i],sizeof(int)); } sort(b,20); out.open("E:\\file.out",ios::out); if(!out) { cout<<"cannot open file\n"; exit(0); } for(i=0;i<20;i++) { out< #include void main() { fstream f("e:\\filein.txt",ios::in|ios::out|ios::binary); int i; for(i=0;i<20;i++) f.write((char *)&i,sizeof(int)); streampos pos=f.tellp(); for(i=20;i<40;i++) f.write((char *)&i,sizeof(int)); f.seekg(pos); f.read((char *)&i,sizeof(int)); cout<<"the data stored is:"< double divide(double,double); void main() { double f1=0.0,f2=0.0; try { cout<<"f1/f2="< using namespace std; void detail(int k) { cout<<"start of detail function.\n"; if(k==0) throw 123; cout<<"end of detail function.\n"; } void compute(int i) { cout<<"start of compute function.\n"; detail(i); cout<<"end of compute function.\n"; } int main() { int x; cout<<"Enter x(0 will throw an exception):"; cin>>x; try { compute(x); } catch(int i) { cout<<"exception:"< using namespace std; void main() { int i; char ch; cout<<"请输入一个整数和一个字符"; try { cin>>i>>ch; if(i==0) throw 0; if(ch=='!') throw '!'; } catch(int) { cout<<"输入为0\n"; } catch(char) { cout<<"输入字符~"; } cout<<"程序结束"; } #include using namespace std; class OutOfBounds { public: OutOfBounds(int a) { i=a;} int indexValue() {return i;} private: int i; }; class Array { public: int &operator[](int i) { if(i<0||i>=10) throw OutOfBounds(i); return a[i]; } private: int a[10]; }; void main() { Array a; try { a[3]=30; cout<<"a[3]"< using namespace std; void h() { throw 0;} void g() {try{h();} catch(int) { cout<<"Catch in g\n"; throw; } } int main() { try{g();} catch(int) { cout<<"Catch in main\n"; } return 0; } #include #include using namespace std; void main() { try { exception theError; throw(theError); } catch(const exception &theError) { cout<
本文档为【C++程序设计编程实例大全】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_591137
暂无简介~
格式:doc
大小:289KB
软件:Word
页数:179
分类:其他高等教育
上传时间:2017-09-18
浏览量:17