C++中*p,&q,m以及**r,*&n,a[],*b[]的通俗易懂解释

30 篇文章 4 订阅

虽然已经码代码有些年头了,但是很多时候,还是容易混淆。今天痛定思痛,突发奇想,条分缕析,算是整明白七七八八了。

一、先整清楚一些关键的概念

  1. 数据在电脑中存储,都是0和1的二进制存储方式,它本身不带任何的数据类型属性。
  2. 那平时我们定义的数据类型,比如int,char,又如何解释呢?那就像是人为定义的一堆方盒子,每个盒子有多大(即多少位),每一位代表的含义(比如最高位是否为正负,比如double的多少位代表底数、指数、尾数之类的,都是人为规定的),然后就可以根据这一长串的0、1,得出这个盒子代表的是一个什么数。同样的一串0、1,放在不同的盒子里,解读出来的值是不一定相同的。
  3. 数据在电脑中存储,包括在内存中的临时存储,都不是乱放的,都是有位置的,我们称之为地址,就像一个个大小相同的快递柜,都有自己的编号,编号就是地址。
  4. 注意,标识快递柜的地址,同时也可能是放在快递柜中的货物,这个存放这地址的快递柜,也有自己的地址,这个地址,换言之,就是想要的数据的地址的地址。也就是说,如果你想要找到这个快递,你拿到的是一个地址的地址,你首先得根据这个地址,打开第一个柜子,获得下一个地址,然后打开第二个柜子,才能拿到东西。以此类推,如果比较淘气一点,你如果想下个连环套,那你可以再多套几环,地址的地址的地址。

二、*p,&q,m的区别和关联

1 区别

  1. 定义变量int *p。*p就是指针,注意,是 * 和p一起,是一个指针,如果只是单独的p,我的理解是,p就是你想要的数据的地址。也就是说,指针不直接指向数据,而是指向存放数据的地址,也就是说这里的p的值,是数据的地址的值。
  2. 定义变量int &q。等同与int q,加不加一个&并没有太大意义。这里&和p如果合在一起看,就是&p,这个时候,也代表了地址,是谁的地址呢,就是数据q的地址,也就是说,这里的&q指向的是数据的地址,而q是具体的数据,int q里的q,也是具体的数据,所以int q和int &q是一个意思。不要复杂化了。实际中,并不会直接定义一个int &q,使用,而是在函数的定义中传参使用,这个后面会细说。
  3. 定义变量int m,这个很明显,m就是数据了。

2 关联

int *p; //定义一个指针    
qDebug()<<p;
int m = 100;  //定义一个普通变量
int q = m;    //定义一个普通变量q,并赋值
p = &q;  //给指针p赋的值,一般是地址
qDebug()<<p;
qDebug()<<*p;
qDebug()<<&q;
qDebug()<<q;

输出的结果如下:

0x56091386e35d
0x7fff9e19aa18
100
0x7fff9e19aa18
100

由上面的结果可以看出来几点:

  1. p代表的确实是地址值,*p代表的地址位置的变量值。
  2. &q输出的值,是变量地址,而q是变量的值。
  3. 地址的值也是一样可以改变的。p的地址值和&q的地址值相同。指针p指向的位置发生了改变。
    总结一下:
  4. 变量值,地址,指针之间是有环环相套、步步为进的关系的。定义一个指针*p,指针指向的地址就是&q,q的值就是变量。这是一个依次展开的过程,当然如果不想要指针,可以直接定义中间一个环节。比如直接定义变量。

3 重点解释

归纳总结出4个解释如下,有点理不清的同志可以熟记:

  1. 前提条件:在计算机中,存在一个这样的关系。有一个具体的数值,有该数值存放的地址,该地址有一个指针指向它。举例说,有一个盒子,盒子里有货物,盒子上有个独一无二的编号,但同时为了方便称呼,这个孩子有一个别的叫法,比如老鱼的盒子。后面的解释,依托此进行层层剖析。
  2. 解释1: *p的解释, *p就是指向地址的指针,即“老鱼的盒子”这个称呼。同时, *p的值就是变量值,即盒子里的货物。
  3. 解释2: p的解释, p就是地址,即盒子这个独一无二的编号。
  4. 解释3: &q的解释, &q就是地址,即盒子这个独一无二的编号。所以&q和p之间可以互相赋值,变化的是地址。
  5. 解释4:q就是变量值,即盒子里的货物。所以q和*p之间可以互相赋值,变化的是变量值。

三、**r,*&n,a[],*b[]的区别

阅读完上述内容后,到了这一部分,理解起来就顺畅了。

1 **的理解

**r,可以拆开解释,先把 * r 当成一体当做p,那么 **r 就成了 * p,根据*p解释,那么p就是地址,最前面解释过,地址也是存储在内存中的值,只是他代表的含义是地址而已,那么再看 *r,r也是地址的值,那么就清楚了,这是套了两层的,地址的地址。

2 *&n的理解

这里,可以将&n理解成一个整体,那根据 *p 解释,&n就是这个p,就是地址值,那么n是什么呢?再来理解一下&n,根据 &q的理解,那么n就是这个q,即一个具体的变量值。所以,绕了半天你会发现,这个 *&n启示就是n。

3 a[]的理解

不要想复杂了,这个就是一个数组。a指向的是这个数组的首地址。

4 *a[]的理解

这个理解起来需要将*a合并理解,也就是将 a看成一个整体。根据上文的p解释,p 就是一个变量值,比如int b=*a,那么a[],就可以理解成b[],那就好理解了。

四、函数传参中的理解

函数传参主要有两种方式,一种是引用,一种是传值。

1 引用

void test1(int &q)
{
{

网上很多教程,都告诉你这p启示就是一个传入的参数的别名,操作的还是原数据,会改变原数据的值。但为什么会这样呢。启示很好理解,把&q当成一个整体,那么根据&q的解释,传入的就是变量存储的地址,所以名称什么的无所谓,管你是老鱼的盒子还是老张的盒子,更重要的盒子编号,即地址已经知道了,你就可以根据这个地址找到内存中的这个变量,然后修改他的值。

2 传值

void test2(int m)
{
{

传值的特点是,不会影响到原来的值,相当于重新复制了一份。这个也很好理解,因为你这个时候传入的参数,就是你盒子里的东西,他没有传入地址,相当于你从盒子里把一个苹果拿了出来,但是你没有记下来你是从哪个盒子拿出来的,盒子这么多,那你吃了一口以后,想放回去也是不可能的了,这样对于数据来说是很不安全的,所以肯定不能让你直接拿走这个苹果,只能让你复制一个苹果走,因为你不知道盒子编号,肯定是还不回来了。

五、启发

  1. 要清楚意识到在计算机中存储的值本身是没有属性的,只是我们人为定义,才加上了属性,无论是变量的值,还是地址的值,还是不同类型的值,都是一样存在计算机内外存中的。
  2. 要熟悉掌握4个解释,清楚几个基本符号之间的关系。
  3. 分析的时候,要习惯把符号和字符分开或者合并理解。
  • 8
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
GreenCppC 2008-8-24 ========================================= // I 类,对象,函数重载 //-------- From C to C++ ------------ // A simple C Program! // convert a string to uppercase! #include <stdio.h> #define N 200 int main(){ char ms[N]; int i; printf("Input ms: "); gets(ms); for(i=0;ms[i];i++) if(ms[i]>='a'&&ms[i]<='z') ms[i]-='\x20'; puts(ms); return 0; } /* path d:\wingw\bin gcc abc.c -o abc.exe */ //------------------------------ // A better C Program! #include <stdio.h> #define N 200 void strUpper(char *s); void strLower(char *s); int main(){ char ms[N]; printf("Input ms: "); gets(ms); strUpper(ms); puts(ms); strLower(ms); puts(ms); return 0; } void strUpper(char *s) { for(;*s;s++) if(*s>='a'&&*s<='z')*s-='\x20'; } void strLower(char *s) { for(;*s;s++) if(*s>='A'&&*s<='Z')*s+='\x20'; } //------------------------------ // A C++ Program without class and object! #include <iostream> using namespace std; const int N=200; void strUpper(char *s); void strLower(char *s); int main(){ char ms[N]; cout<<"Input ms: "; cin.getline(ms,N); strUpper(ms); cout<<ms<<"\n"; strLower(ms); cout<<ms<<endl; return 0; } void strUpper(char *s) { for(;*s;s++) if(*s>='a'&&*s<='z')*s-='\x20'; } void strLower(char *s) { for(;*s;s++) if(*s>='A'&&*s<='Z')*s+='\x20'; } //------------------------------ // A C++ Program with class and object! #include <iostream> using namespace std; const int N=200; class Str{ char s[N]; public: void out(){cout<<s<<"\n";} void in(){cout<<"s: "; cin.getline(s,N);} void upper(); void lower(); }; void Str::upper() {char *p; for(p=s;*p;p++) if(*p>='a'&&*p<='z')*p-='\x20'; } void Str::lower() { for(char *p=s;*p;p++) if(*p>='A'&&*p<='Z')*p+='\x20'; } // - - - int main(){ Str a; cin>>a.s; //error! a.in(); a.upper(); a.out(); a.lower(); a.out(); return 0; } ========================================= // II. 构造与析构函数 #include <iostream> #include <cstring> using namespace std; class child { char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); ~child(); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *name,int age){ strcpy(this->name,name); this->age=age; // this -- address of self object } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int age){ if(this->age==age) cout<<"Yes, i am "<<age<<" years old.\n"; else cout<<"No, i am not "<<age<<" years old.\n"; } // --- child::~child(){ cout<<name<<": Bye!\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.age=4; // error! tom.ask("tom"); rose.ask("Alice"); tom.ask(2); return 0; } ========================================= // III. 继承 #include <iostream> #include <cstring> using namespace std; class child { protected: //note this change! char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *n,int a){ strcpy(name,n); age=a; } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int a){ if(a==age) cout<<"Yes, i am "<<a<<" years old.\n"; else cout<<"No, i am not "<<a<<" years old.\n"; } // ----------- class pupil: public child{ char book[20]; public: pupil(char *n,int a,char *b); void list(); }; // --- pupil::pupil(char *n,int a,char *b): child(n,a) { strcpy(book,b); } // --- void pupil::list() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.ask("tom"); rose.ask("Alice"); tom.ask(2); pupil green("Green",9,"Nature"); green.ask("Jack"); green.ask(10); green.list(); return 0; } ========================================= // IV. 增加与基类成员函数同名的函数; // 调用基类成员函数;内联函数(in-line) #include <iostream> #include <cstring> using namespace std; class child { protected: char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *n,int a){ strcpy(name,n); age=a; } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int a){ if(a==age) cout<<"Yes, i am "<<a<<" years old.\n"; else cout<<"No, i am not "<<a<<" years old.\n"; } // ----------- class pupil: public child{ char book[20]; public: pupil(char *n,int a,char *b); void ask(char *n){child::ask(n);} // in-line! void ask(int a){child::ask(a);} void ask(); }; // --- pupil::pupil(char *n,int a,char *b): child(n,a) { strcpy(book,b); } // --- void pupil::ask() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.ask("tom"); rose.ask("Alice"); tom.ask(2); pupil green("Green",9,"Nature"); green.ask("Jack"); green.ask(10); green.ask(); return 0; } ===================================== // V. 对象数组 #include <iostream> using namespace std; class C1{ int a,b; public: C1(int m,int n){a=m;b=n;} int getAdd(){return a+b;} }; int main() {C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}; int i; for(i=0;i<3;i++) cout << ob[i].getAdd() << " "; // C1 oe[2]; -- Error! means constructor is C1() // -- need reload C1::C1(){ ... } // -- eg, C1::C1(){a=b=0;} return 0; } ========================================= // VI. 指向对象的指针 C1 obA(2,3), *p; p=&obA; cout << p->getAdd(); //------------- C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}, *q; q=ob; for(int i=0;i<3;i++) {cout << q->getAdd() << " "; q++; } //------------- class C2{ public: int a; C2(int k){a=k*k;} }; // . . . C2 obB(9); int *p; p=&obB.a; // Note! a is public, p to member cout << *p; // 指向派生类的指针 class Base{ public: int a,b; Base(int m,int n){a=m;b=n;} int getAdd(){return a+b;} }; class Derived: public Base{ int c; public: Derived(int x,int y,int z): Base(x,y) {c=z;} float getAve(){return (a+b+c)/3.0F;} }; // ... Base *bp; Derived d(6,7,9); bp=&d; cout << bp->getAdd(); cout << bp->getAve(); // Error! cout << ((Derived *) bp) ->getAve(); ========================================= // VII. 动态分配:new, delete #include <iostream> #include <new> using namespace std; int main() {int *p; try{ p=new int; } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } *p=20; cout << "At "<<p<<" is "<< *p <<"\n"; delete p; return 0; } //------------- #include <iostream> #include <new> using namespace std; int main() {int *p; try{ p=new int[6]; } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } float ave=0.0F; int i; cout<<"Enter numbers: "; for(i=0;i<6;i++) {cin>>p[i]; ave+= *(p+i); cout<< *(p+i); } ave/=6.0F; cout << "Ave = "<< ave <<"\n"; delete [] p; return 0; } //------------- #include <iostream> #include <cstring> #include <new> using namespace std; class Balance{ char name[40]; double curValue; public: Balance(char *n,double v){ strcpy(name,n); curValue=v; } void getValue(char *n,double &v){ strcpy(n,name); v=curValue; } }; int main() { Balance *p; char s[40]; double bal; try{ p=new Balance("Robin Hood",3536.45); } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } p->getValue(s,bal); cout<<s<<"\'s balance is "<<bal<<"\n"; delete p; return 0; } ========================================= // VIII. 传递引用 #include <iostream> using namespace std; void neg1(int k); void neg2(int *p); void neg3(int &k); int main() { int x=20; neg1(x); neg2(&x); cout << x<< "\n"; neg3(x); cout << x<< "\n"; } // - - - void neg1(int k) { k=-k;} void neg2(int *p) { *p=-*p;} void neg3(int &k) { k=-k; } //------------- #include <iostream> using namespace std; class C1{ public: int k; void neg(C1 &o){o.k=-o.k;} // -- no temp object created }; int main() { C1 ob; ob.k=20; ob.neg(ob); cout << ob.k <<"\n"; return 0; } //----------------------------------- /* Input a sentence,reverse all the words except other chars, eg: etihw, dna kcalb! => white, and black! NOT: !black and ,white */ #include <iostream> #include <new> #include <cstdlib> #include <cctype> using namespace std; const int N=200; /* - - - - - - */ class CharStack{ const int StkLen; char *data; int top; public: CharStack(); ~CharStack(){delete []data;} int push(char x) {if(top>=StkLen-1)return -1; // it's full top++; data[top]=x; return 0; } int pop(char &x) {if(top<=-1)return -1; // empty! x= *(data+top); top--; return 0; } }; CharStack::CharStack():StkLen(40) {try{ data=new char[StkLen]; }catch(bad_alloc){cout<<"New failed!"; exit(-1);} top=-1; } // --------- class WordRev{ char ms[N]; public: void reads() { cout<<"Input str:\n"; cin.getline(ms,N); } void prints() { cout<<ms<<"\n"; } void wRev(); }; void WordRev::wRev() {CharStack stk; int i=0,wStart,wEnd; while(ms[i]) {if(!isalpha(ms[i]))i++; else {wStart=i; while(isalpha(ms[i]))stk.push(ms[i++]); wEnd=i; i=wStart; while(!stk.pop(ms[i]))i++; i=wEnd; } } } // --------- int main() { WordRev sr; sr.reads(); sr.wRev(); sr.prints(); return 0; } ========================================= // IX 函数形参使用默认值 #include <iostream> #include <cstring> using namespace std; // ----------- class pupil{ public: char name[20]; int age; char book[20]; pupil(char *n,int a,char *b); void list(); }; // --- pupil::pupil(char *n,int a,char *b){ strcpy(name,n); age=a; strcpy(book,b); } // --- void pupil::list() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- void nextYear(pupil &c,char *book="Math"); //---------- int main(){ pupil green("Green",9,"Chinese"); green.list(); nextYear(green); green.list(); nextYear(green,"Nature"); green.list(); return 0; } //---------- void nextYear(pupil &c,char *book="Math") { // ="Math" Should be omitted, for previous prototype c.age++; strcpy(c.book,book); return; } /* D:\green>g++ pupil.cpp -o pupil.exe pupil.cpp: In function `void nextYear(pupil&, char*)': pupil.cpp:41: error: default argument given for parameter 2 of `void nextYear(pupil&, char*)' pupil.cpp:25: error: after previous specification in `void nextYear(pupil&, char*)' */ ========================================= // X. 虚函数 virtual #include <iostream> using namespace std; class base{ public: virtual void vf(){cout<<"base's vf.\n";} }; class derived1:public base{ public: virtual void vf(){cout<<"derived1's vf.\n";} }; class derived2:public base{ public: virtual void vf(){cout<<"derived2's vf.\n";} }; void f(base &r){r.vf();} int main() {base b, *p; derived1 d1; derived2 d2; b.vf(); d1.vf(); d2.vf(); p=&b; p->vf(); p=&d1; p->vf(); // derived1's vf. p=&d2; p->vf(); // derived2's vf. f(b); f(d1); // derived1's vf. f(d2); // derived2's vf. return 0; } ========================================= // XI. 对象赋值问题 #include <iostream> #include <cstdlib> #include <new> using namespace std; class Myclass{ int *p; public: Myclass(int i); void show(){cout<< *p<<"\n";} ~Myclass(){delete p;} }; Myclass::Myclass(int i){ try{ p=new int; } catch(bad_alloc e) {cout<< "New failed!\n"; exit(-1); } *p=i; } int main() {Myclass a(20); Myclass b=a; //copy by bits b.show(); return 0; // 错误!对象 p 所指向的内存空间将被释放 2 次! } ========================================= // XII. 拷贝构造函数 ---- 解决对象参数传递的副作用问题 #include <iostream> #include <new> using namespace std; class array{ public: int *p; int size; array( ){p=NULL;size=0; }; array(int sz); array(const array &a); ~array(){if(!p){delete [ ]p; size=0;}} void input(); }; array::array(int sz){ size=sz; try{ p=new int[size]; }catch (bad_alloc xa){ cout <<"Alloc failed!"; exit(EXIT_FAILURE); } } array::array(const array &a){ try{ p=new int[a.size]; }catch (bad_alloc xa){ cout <<"Alloc failed!"; exit(EXIT_FAILURE); } size=a.size; for(int i=0;i<size;i++)p[i]=a.p[i]; } void array::input(){ cout<<"Input "<<size<<" integers: "; for(int i=0;i<size;i++)cin>>p[i]; } void inc(array a){ int i; for(i=0;i<a.size;i++) if(a.p[i]==59)a.p[i]++; cout<<"Result is: " ; for(i=0;i<a.size;i++)cout<<a.p[i]<<' '; cout<<"\n"; } int main(){ array a(4),c; a.input(); array b(a); // 调用拷贝构造函数 inc(b); //调用拷贝构造函数(隐式) for(int i=0;i<b.size;i++)cout<<b.p[i]<<' '; return 0; } ========================================= // XIII. 运算符重载 #include <iostream> using namespace std; class loc{ int longitude,latitude; public: loc(){} //needed to construct temp objects loc(int lg,int lt){longitude=lg; latitude=lt;} void show(){cout<<longitude<<" "<<latitude<<"\n";} loc operator+(loc op2); loc operator++(); loc operator=(loc op2); loc operator+=(loc op2); }; loc loc::operator+(loc op2) {loc temp; temp.longitude=op2.longitude+longitude; temp.latitude=op2.latitude+latitude; return temp; } loc loc::operator++() //前缀形式 prefix {longitude++; latitude++; return *this; } loc loc::operator=(loc op2) { longitude=op2.longitude; latitude=op2.latitude; return *this; //为连续赋值 } loc loc::operator+=(loc op2) { longigude=op2.longitude+longitude; latitude=op2.latitude+latitude; return *this; //为连续赋值 } // operator=和operator++等都改变了对象的值 int main() {loc ob1(10,20),ob2(5,30),ob3; ob3=ob1+ob2; ++ob3; ob3.show(); ob1+=ob2; ob1=ob1+ob2; // ob1.+(ob2) like (ob1+ob2).show(); ++ob1; ob1=ob2=ob3; ... ... } ========================================= // XIV. 异常的抛出,捕获与处理 #include <iostream> using namespace std; int main() {cout <<"Start\n"; try { cout << "Inside try block\n"; throw 100; cout << "This will not execute"; } catch (int i) { cout << "Caught an exception, value is: "; cout << i <<"\n"; } cout << "End\n"; return 0; } // -------------------- #include <iostream> using namespace std; void xtest(int test) { cout << "Inside xtest!\n"; if(test) throw test; } int main() {cout <<"Start\n"; try { cout << "Inside try block\n"; xtest(0); xtest(1); xtest(2); } catch (int i) { cout << "Caught an exception, value is: "; cout << i <<"\n"; } cout << "End\n"; return 0; } // 捕获异常类 #include <iostream> #include <cstring> using namespace std; class MyException{ public: char how[80]; int what; MyException(){*how=0; what=0;} MyException(char *s, int n) {strcpy(how,s); what=n; } }; int main() {int i; try { cout <<"Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive",i); } catch (MyException e) { cout << e.how<<": "; cout << e.what <<"\n"; } return 0; } // 捕获派生异常类 #include <iostream> using namespace std; class B { }; class D: public B { }; int main() {D derived; try { throw derived; } catch (D d) { cout << "Caught a derived class, not the base! \n"; } catch (B b) { cout << "Caught the base class! \n"; } return 0; } // 异常的限制及捕获所有异常 #include <iostream> using namespace std; void xtest(int test) throw (int,char,double,char *) { try { if(test==0) throw test; if(test==1) throw 'a'; if(test==2) throw 12.34; if(test==3) throw "A string."; } catch (int i) { cout << "Caught an integer!"; } catch (...) { cout << "Caught Another!"; } } int main() {cout <<"Start\n"; xtest(0); xtest(1); xtest(2); xtest(3); cout << "End\n"; return 0; } // 异常的再次抛出 #include <iostream> using namespace std; void xhandler() { try { throw "Hello!"; } catch (const char *) { cout << "Caught a string inside!\n"; throw; //rethrow char * out of function } } int main() {cout <<"Start\n"; try { xhandler(); } catch (const char *) { cout << "Caught a string outside!\n"; } cout << "End\n"; return 0; } // 一个简单的程序 #include <iostream> using namespace std; int main() {int a,b; cout <<"Enter a b: "; cin >> a >> b; try { if(!b) throw b; cout << "Result: "<< a/b << endl; } catch (int i) { cout << "Can't divide by zero!\n"; } return 0; } ========================================= XV. 模板 //模板之通用函数 #include <iostream> using namespace std; template <class X> void superSwap(X &a, X &b) { X t; t=a; a=b; b=t; }; int main() { int m=10, n=20; double x=10.1, y=20.2; char a='A', b='\x42'; superSwap(m,n); superSwap(x,y); superSwap(a,b); cout<<"m="<<m<<", n="<<n<<'\n'; cout<<"x="<<x<<", y="<<y<<'\n'; cout<<"a="<<a<<", b="<<b<<'\n'; return 0; } ---------------------------------- #include <iostream> using namespace std; template <class type1,class type2> void myfunc(type1 x, type2 y) { cout<<x<<' '<<y<<'\n'; } int main() { myfunc("C++ is great!", 100); // char* , int myfunc(1234.56, 20L); // double , long int return 0; } // 模板之通用类 #include <iostream> using namespace std; const int Size=20; template <class DataType> class SuperStack{ DataType data[Size]; int top; public: SuperStack(){top= -1;} int push(DataType x); int pop(DataType &x); }; template <class DataType> int SuperStack<DataType>::push(DataType x) { if(top>=Size-1) return -1; // stack is full data[++top]=x; return 0; } template <class DataType> int SuperStack<DataType>::pop(DataType &x) { if(top<0) return -1; // stack is empty x=data[top--]; return 0; } int main() { SuperStack<char> chStack; SuperStack<double> dbStack; char s[Size]="ABC"; double a[Size]={20.1, 21.2, 22.3}; int i; for(i=0;i<3;i++) { chStack.push(s[i]); dbStack.push(a[i]); } for(i=0;i<3;i++) { chStack.pop(s[i]); dbStack.pop(a[i]); } cout << s << '\n'; for(i=0;i<3;i++) cout << a[i]<<' '; cout<<'\n'; return 0; } ========================================= XVI. 名字空间 #include <iostream> using namespace std; namespace GreenNamespace{ char Say[80]="TRUTH, Must thou Know!"; bool isUpperLetter(char ch) { if(ch>='A' &&ch<='Z')return true; return false; } class X{ public: int year; X(int y){year=y;} }; // note this semi-colon! } using namespace GreenNamespace; int main() {cout << Say <<'\n'; char *p=Say; int count=0; for(;*p;p++) if(isUpperLetter(*p))count++; cout << "count = " << count <<'\n'; X ob(2006); cout << ob.year <<"\n"; return 0; } //------------------------ ////////// OneCount.cpp//////// namespace BitsSpace{ int onePerByte(char x); int oneCount(char *buf,int bytes); // ------------------- int onePerByte(char x) {int count=0,i; for(i=0;i<8;i++) {if(x & '\x1') count++; // 'A'<=> '\x41' x>>=1; //x=x>>1; } return count; } // --- int oneCount(char *buf,int bytes) {int count=0,i; for(i=0;i<bytes;i++) count+=onePerByte(buf[i]); return count; } // --- } ---------------- ////////// testOne.cpp//////// #include <iostream> #include "OneCount.cpp" using namespace std; //using namespace BitsSpace; const int SLen=80; // ---- int main(){ char ms[SLen],*p; cout<<"Enter your words:\n> " ; cin.getline(ms,SLen); cout<< BitsSpace::oneCount(ms,strlen(ms))<<"\n"; cout<<"Size of char: "<<sizeof(char)<<"\n"; return 0; } ========================================= //////////////////////////////// // XVII. C++ file handle, 6 programs // by Hs.li 2007.4.28 //////////////////////////////// // Write text strings! #include <iostream> #include <fstream> using namespace std; #define MaxN 200 // - - - - - - int main() {fstream outF; char text[MaxN]; cout<<"Enter lines, end with empty line:\n"; outF.open("str.txt",ios::out); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } while(1) { cin.getline(text,MaxN); if(!text[0])break; outF<<text<<"\n"; if(outF.bad()||outF.fail()) {cout<<"Write file error!\n"; outF.close(); return -2; } } cout<<"Write text file okey!\n"; outF.close(); return 0; } ========================= // Read text strings! #include <iostream> #include <fstream> using namespace std; #define MaxN 200 // - - - - - - int main() {fstream inF; char text[MaxN]; cout<<"The text lines are:\n"; inF.open("str.txt",ios::in); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } while(1) { inF.getline(text,MaxN); if(inF.eof()|inF.fail()|inF.bad())break; cout<<text<<"\n"; } if(!inF.eof()) {cout<<"Read file error!\n"; inF.close(); return -2; } cout<<"---- End!\n"; inF.close(); return 0; } ====================== // Write text data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { const int MaxN=8; fstream outF; double a[MaxN]; char *fname="data.txt"; int i; cout<<"Please input 8 double: "; for(i=0;i<MaxN;i++) cin>>a[i]; outF.open(fname,ios::out); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } outF.exceptions(fstream::failbit| fstream::badbit); try{ for(i=0;i<MaxN;i++) outF<<a[i]<<" "; } catch(std::exception &e) {cout<<"Exception caught:"<<e.what()<<endl; outF.close(); return -2; } outF.close(); cout<<"Text data file write okey!\n"; return 0; } ============================ // Read text data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { fstream inF; double b; char *fname="data.txt"; cout<<"Please wait for reading data:\n"; inF.open(fname,ios::in); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } inF.exceptions(fstream::failbit| fstream::badbit|fstream::eofbit); try{ while(1) { inF>>b; cout<<b<<" "; } }catch(std::exception &e) { if(!inF.eof()) { cout<<"Exception caught:"<<e.what()<<endl; inF.close(); return -2; } } inF.close(); cout<<"\nText data file read okey!\n"; return 0; } =============================== // Write binary data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { const int MaxN=8; fstream outF; double a[MaxN]; char *fname="data.dat"; int i; cout<<"Please input 8 double: "; for(i=0;i<MaxN;i++) cin>>a[i]; outF.open(fname,ios::out|ios::binary); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } outF.exceptions(fstream::failbit| fstream::badbit); try{ outF.write((char *)a,MaxN*sizeof(double)); } catch(std::exception &e) {cout<<"Exception caught:"<<e.what()<<endl; outF.close(); return -2; } outF.close(); cout<<"Binary data file write okey!\n"; return 0; } ================================ // Read binary data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { fstream inF; double b; char *fname="data.dat"; cout<<"Please wait for reading data:\n"; inF.open(fname,ios::in|ios::binary); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } inF.exceptions(fstream::failbit| fstream::badbit|fstream::eofbit); try{ while(1) { inF.read((char *)&b,sizeof(double)); cout<<b<<" "; } }catch(std::exception &e) { if(!inF.eof()) { cout<<"Exception caught:"<<e.what()<<endl; inF.close(); return -2; } } inF.close(); cout<<"\nBinary data file read okey!\n"; return 0; } ////////////////////////////////////////////////
#include <graphics.h> #include <stdlib.h> #include <dos.h> #include <conio.h> #include <math.h> #include <malloc.h> #define G 9.8 /*重力加速度*/ #define PI 3.141593 /*圆周率*/ #define L1 60 /*小屋运动的范围*/ #define T1 100 #define R1 200 #define B1 450 #define AMD1 5 /*修订数*/ #define AMD2 1.78 /*修订数*/ /*鼠标信息宏定义*/ #define WAITING 0xff00 #define LEFTPRESS 0xff01 #define LEFTCLICK 0xff10 #define LEFTDRAG 0xff19 #define RIGHTPRESS 0xff02 #define RIGHTCLICK 0xff20 #define RIGHTDRAG 0xff2a #define MIDDLEPRESS 0xff04 #define MIDDLECLICK 0xff40 #define MIDDLEDRAG 0xff4c #define MOUSEMOVE 0xff08 int Keystate; int MouseExist; int MouseButton; int MouseX; int MouseY; int up[16][16],down[16][16],mouse_draw[16][16],pixel_save[16][16]; void MouseMath()/*计算鼠标的样子*/ { int i,j,jj,k; long UpNum[16]={ 0x3fff,0x1fff,0x0fff,0x07ff, 0x03ff,0x01ff,0x00ff,0x007f, 0x003f,0x00ff,0x01ff,0x10ff, 0x30ff,0xf87f,0xf87f,0xfc3f }; long DownNum[16]={ 0x0000,0x7c00,0x6000,0x7000, 0x7800,0x7c00,0x7e00,0x7f00, 0x7f80,0x7e00,0x7c00,0x4600, 0x0600,0x0300,0x0300,0x0180 }; for(i=0;i<16;i++) { j=jj=15; while(UpNum[i]!=0) { up[i][j]=UpNum[i]%2; j--; UpNum[i]/=2; } while(DownNum[i]!=0) { down[i][jj--]=DownNum[i]%2; DownNum[i]/=2; } for(k=j;k>=0;k--) up[i][k]=0; for(k=jj;k>=0;k--) down[i][k]=0; for(k=0;k<16;k++)/*四种组合方式*/ { if(up[i][k]==0&&down;[i][k]==0) mouse_draw[i][k]=1; else if(up[i][k]==0&&down;[i][k]==1) mouse_draw[i][k]=2; else if(up[i][k]==1&&down;[i][k]==0) mouse_draw[i][k]=3; else mouse_draw[i][k]=4; } } mouse_draw[1][2]=4;/*特殊点*/ } /*鼠标光标显示*/ void MouseOn() { int x=MouseX,y=MouseY; int i,j; int color; for(i=0;i<16;i++)/*画鼠标*/ { for(j=0;j<16;j++) { pixel_save[i][j]=getpixel(x+j,y+i);/*保存原来的颜色*/ if(mouse_draw[i][j]==1) putpixel(x+j,y+i,0); else if(mouse_draw[i][j]==2) putpixel(x+j,y+i,15); } } } /*隐藏鼠标*/ void MouseOff() { int i,j,x,y,color; x=MouseX; y=MouseY; for(i=0;i<16;i++)/*原位置异或消去*/ for(j=0;j<16;j++) { if(mouse_draw[i][j]==3||mouse_draw[i][j]==4) continue; color=getpixel(x+j,y+i); putpixel(x+j,y+i,color^color); putpixel(x+j,y+i,pixel_save[i][j]); } } /*鼠标状态值初始化*/ void MouseReset() { _AX=0x00; geninterrupt(0x33); } /*设置鼠标左右边界 lx:左边界 rx:右边界 */ void MouseSetX(int lx,int rx) { _CX=lx; _DX=rx; _AX=0x07; geninterrupt(0x33); } /*设置鼠标上下边界 uy:上边界 dy:下边界 */ void MouseSetY(int uy,int dy) { _CX=uy; _DX=dy; _AX=0x08; geninterrupt(0x33); } /*设置鼠标当前位置 x:横向坐标 y:纵向坐标 */ void MouseSetXY(int x,int y) { _CX=x; _DX=y; _AX=0x04; geninterrupt(0x33); } /*获取鼠标按下键的信息*/ /*是否按下左键 返回值: 1=按下 0=释放*/ int LeftPress() { _AX=0x03; geninterrupt(0x33); return(_BX&1); } /*是否按下键 返回值同上 */ int MiddlePress() { _AX=0x03; geninterrupt(0x33); return(_BX&4); } /*是否按下右键 返回值同上 */ int RightPress() { _AX=0x03; geninterrupt(0x33); return(_BX&2); } /*获取鼠标当前位置*/ void MouseGetXY() { _AX=0x03; geninterrupt(0x33); MouseX=_CX; MouseY=_DX; } /*鼠标按键情况,返回0表示只移动,返回1表示左右键同时按下,2表示只按了左键,3表示只按了右键*/ int MouseStatus() { int x,y; int status; int press=0; int i,j,color; status=0;/*默认鼠标没有移动*/ x=MouseX; y=MouseY; while(x==MouseX&&y==MouseY&&status;==0&&press;==0) { if(LeftPress()&&RightPress;()) press=1; else if(LeftPress()) press=2; else if(RightPress()) press=3; MouseGetXY(); if(MouseX!=x||MouseY!=y) status=1; } if(status)/*移动情况才重新显示鼠标*/ { for(i=0;i<16;i++)/*原位置异或消去*/ for(j=0;j<16;j++) { if(mouse_draw[i][j]==3||mouse_draw[i][j]==4) continue; color=getpixel(x+j,y+i); putpixel(x+j,y+i,color^color); putpixel(x+j,y+i,pixel_save[i][j]); } MouseOn();/*新位置显示*/ } if(press!=0)/*有按键的情况*/ return press; return 0;/*只移动的情况*/ } /*定义玩家的结构体*/ struct Ren{ int x,y; int life; int color; int lr;/*1表示左,2表示右。*/ }; /*绘制游戏界面*/ void Desktop() { setcolor(14); line(320,0,320,480); rectangle(L1-20,T1-40,R1+20,B1+10); rectangle(640-(R1+20),(T1-40),640-(L1-20),B1+10); outtextxy(25,20,"P1"); outtextxy(345,20,"P2"); } /*把一个数字n转换成字符串,并存储在a,带符号+-*/ void numtostr(int n,char a[5]) { int w,e; e=n; n=abs(n); a[3]=(n)+'0'; w=n/10; a[2]=(w)+'0'; w=w/10; a[1]=(w)+'0'; a[4]='\0'; if(e<0) a[0]='-'; else a[0]='+'; } /*把速度和角度装换成字符串输出*/ void AngleSpeed(double s,double angle) { int ss,aa; char zzs[5],zza[5]; int left,top,right,bottom; left=275; top=50; right=left+90; bottom=top+10; ss=(int)(s); aa=(int)((angle)*180/PI); numtostr(ss,zzs); numtostr(aa,zza); setfillstyle(1,15); setcolor(10); bar(left,top,right,bottom); outtextxy(left+5,top+3,zzs); outtextxy((left+right)/2+5,top+3,zza); circle(right-6,top+3,2); } /*实现人机对抗的函数*/ void Fire (int a[4],double *v,double *angle,int n)/*a数组存放对射的两点,v和angle存放机器射击的角度和速度,n表式机器射击的准确度*/ { int t; double vx,vy; double sx,sy; int m; m=12*4/n; randomize(); m=random(m)-m/2; t=20; sx=(double)(a[2]-a[0]); sy=(double)(a[3]-a[1]); vx=sx/(double)(t); vy=(sy-0.5*PI*(double)(t*t))/(double)(t); *angle=atan((-vy)/vx); *v=sqrt(vx*vx+vy*vy); *v=(*v)*(AMD2+0.01*(double)(m)); AngleSpeed(*v,*angle); } /*绘制生命线的函数*/ void LifePicture(int life,int color,int location) { char lm[5]; int l,t,r,b; l=50; t=20; r=l+200; b=t+10; numtostr(life,lm); setfillstyle(1,color); setcolor(15); if(location==1||location==3) { bar(l,t,r,b); setfillstyle(1,4); bar(l,t+(b-t)/4,l+life,t+3*(b-t)/4); setfillstyle(1,color); bar(r+10,t,r+50,b); outtextxy(r+10+5,t+2,lm); } else { l=320+50; r=l+200; bar(l,t,r,b); setfillstyle(1,4); bar(l,t+(b-t)/4,l+life,t+3*(b-t)/4); setfillstyle(1,color); bar(r+10,t,r+50,b); outtextxy(r+10+5,t+2,lm); } } /*绘制小屋的函数*/ void RenPicture(int x,int y,int color) { setcolor(color); setwritemode(1); line(x,y-40,x-10,y-30);/*画头*/ line(x,y-40,x+10,y-30); line(x-10,y-30,x+10,y-30); line(x-5,y-30,x-5,y-10);/*画脖子*/ line(x+5,y-30,x+5,y-10); line(x-20,y-10,x+20,y-10);/*画身子*/ line(x-20,y+10,x+20,y+10); line(x-20,y-10,x-20,y+10); line(x+20,y-10,x+20,y+10); } /*绘制箭的函数*/ void PictureBullets (int wx,int wy,int tx,int ty) { setcolor(RED); line(wx,wy,tx,ty); line(wx-1,wy-1,tx,ty); line(wx+1,wy+1,tx,ty); } /*绘制小屋上箭的函数*/ void InitialArrow (int x,int y,int a[4]) { int addx,addy; addx=(a[2]-a[0])/6; addy=(a[3]-a[1])/6; PictureBullets(x+addx,y+addy,x,y); } /*判断点qx,qy在直线的什么位置*/ int PointPlace(int qx,int qy,int x1,int y1,int x2,int y2)/*返回0表示在直线上,当斜率存在时:1表示在直线的上面,2表示在直线的下面,当斜率不存在时:3表示在左面,4表示在右面*/ { int s; if(x1==x2) { if(qx<x1) return 3; else if(qx>x1) return 4; else return 0; } else { s=(int)(((double)(y1-y2))/((double)(x1-x2))*((double)(qx-x1))+(double)(y1)); if(qy<s) return 1; else if(qy>s) return 2; else return 0; } } /*根据两点坐标计算出两点距离和斜率。*/ void DistanceAngle (int twoxy1[4],double *distance,double *angle) { double a,b; if(twoxy1[0]!=twoxy1[2]) { a=(double)((double)((double)twoxy1[3]-(double)twoxy1[1])/(double)((double)twoxy1[0]-(double)twoxy1[2])); *angle=atan(a); if(twoxy1[0]<twoxy1[2]) *angle=PI+(*angle); } else if(twoxy1[1]<twoxy1[3]) *angle=PI/2; else *angle=-PI/2; b=(double)((double)(twoxy1[3]-twoxy1[1])*(double)(twoxy1[3]-twoxy1[1])+(double)(twoxy1[2]-twoxy1[0])*(double)(twoxy1[2]-twoxy1[0])); *distance=sqrt(b); } /*由速度角度算sx,sy随时间的变化*/ void RelativePosition(int *sx,int *sy,double v,double angle,double t) { *sx=(int)((v*cos(angle))*t); *sy=(int)((v*sin(angle))*t-0.5*G*t*t); } /*用鼠标画一条直线,把直线的两点坐标放在twoxy数组内。*/ void TwoPoints(int twoxy[4],int dx,int dy) { int i,q=1; int ddx=dx,ddy=dy; double speed=0.0,angle=0.0; twoxy[0]=0; twoxy[1]=0; setcolor(13); line(dx,dy+30,dx,dy-30); line(dx-30,dy,dx+30,dy); setcolor(4); MouseOn();/*显示鼠标*/ setwritemode(1); i=0; while(q) { if(i==1) { MouseOff(); DistanceAngle(twoxy,&speed;,&angle;); AngleSpeed(speed/AMD1,angle); InitialArrow (ddx,ddy,twoxy); setcolor(4); line(twoxy[0],twoxy[1],twoxy[2],twoxy[3]); MouseOn(); if((twoxy[2]!=MouseX)||(twoxy[3]!=MouseY)) { twoxy[2]=MouseX; twoxy[3]=MouseY; MouseOff(); DistanceAngle(twoxy,&speed;,&angle;); AngleSpeed(speed/AMD1,angle); InitialArrow (ddx,ddy,twoxy); setcolor(4); line(twoxy[0],twoxy[1],twoxy[2],twoxy[3]); MouseOn(); } } if(MouseStatus()) { sound(1000);/*响声函数*/ delay(10000); nosound(); delay(1000000); delay(1000000); delay(1000000); delay(1000000); if(i==0) { twoxy[0]=MouseX; twoxy[1]=MouseY; twoxy[2]=MouseX; twoxy[3]=MouseY; i=1; } else { MouseOff(); DistanceAngle(twoxy,&speed;,&angle;); AngleSpeed(speed/AMD1,angle); InitialArrow (ddx,ddy,twoxy); setcolor(4); line(twoxy[0],twoxy[1],twoxy[2],twoxy[3]); setcolor(13); line(dx,dy+30,dx,dy-30); line(dx-30,dy,dx+30,dy); q=0; i=0; } } } } /*发射箭,speed1和speed2控制速度,返回弹位置*/ int Launch(int lx,int ly,int tx,int ty,int hm,int grade) { double speed1=0.01; int speed2=1000; int a[4]; int xx[2],xy[2]; double s=0.0,angle=0.0,t=0.0; lx=lx;ly=ly-50; if(hm==3) { a[0]=lx; a[1]=ly; a[2]=tx; a[3]=ty; Fire (a,&s,&angle;,grade); } else { TwoPoints(a,lx,ly); DistanceAngle(a,&s,&angle;); s=s/AMD1; } RelativePosition(&xx;[0],&xy;[0],s,angle,t-1); RelativePosition(&xx;[1],&xy;[1],s,angle,t); for(t=0.0;ly-xy[1]<480;t=t+speed1) { RelativePosition(&xx;[0],&xy;[0],s,angle,t-1); RelativePosition(&xx;[1],&xy;[1],s,angle,t); if(PointPlace(lx+xx[1],ly-xy[1],tx,ty-40,tx+10,ty-30)==2&&PointPlace;(lx+xx[1],ly-xy[1],tx,ty-40,tx-10,ty-30)==2&&PointPlace;(lx+xx[1],ly-xy[1],tx-10,ty-30,tx+10,ty-30)==1) { sound(4000);/*响声函数*/ delay(10000); nosound(); return 1; } if(PointPlace(lx+xx[1],ly-xy[1],tx-5,ty-30,tx+5,ty-30)==2&&PointPlace;(lx+xx[1],ly-xy[1],tx-5,ty-10,tx+5,ty-10)==1&&PointPlace;(lx+xx[1],ly-xy[1],tx-5,ty-30,tx-5,ty-10)==4&&PointPlace;(lx+xx[1],ly-xy[1],tx+5,ty-30,tx+5,ty-10)==3) { sound(3000);/*响声函数*/ delay(10000); nosound(); return 2; } if(PointPlace(lx+xx[1],ly-xy[1],tx-20,ty-10,tx-20,ty+10)==4&&PointPlace;(lx+xx[1],ly-xy[1],tx+20,ty-10,tx+20,ty+10)==3&&PointPlace;(lx+xx[1],ly-xy[1],tx-20,ty-10,tx+20,ty-10)==2&&PointPlace;(lx+xx[1],ly-xy[1],tx-20,ty+10,tx+20,ty+10)==1) { sound(2000);/*响声函数*/ delay(10000); nosound(); return 3; } if(ly-xy[1]<1) { delay(speed2); continue; } if(lx+xx[1]<1||lx+xx[1]>640-1) { return 0; } PictureBullets (lx+xx[0],ly-xy[0],lx+xx[1],ly-xy[1]); delay(speed2); PictureBullets (lx+xx[0],ly-xy[0],lx+xx[1],ly-xy[1]); } return 0; } /*小屋移动的函数*/ int MoveRen(struct Ren *p) { int a,k=19200,b=0,d; int q=1; randomize(); for(;q;) { if(b==1) { p->lr=3; } RenPicture(p->x,p->y,p->color); if(p->lr==3) { b=1; delay(10000); delay(10000); delay(10000); delay(10000); delay(10000); delay(10000); //sleep(1); d=random(10); if(d==0) k=19200; if(d==1) k=19712; if(d==2) k=18432; if(d==3) k=20480; if(d==4) k=7181; p->lr=1; } else { k=bioskey(0); } RenPicture(p->x,p->y,p->color); switch(k){ case 19200: /*按向左键*/ a=(p->x)-5; if(p->lr==1) { if(a>L1&&a<R1) { p->x=a; break; } } else { if(a>640-R1&&a<640-L1) { p->x=a; break; } } break; case 19712: /*按向右键*/ a=(p->x)+5; if(p->lr==1) { if(a>L1&&a<R1) { p->x=a; break; } } else { if(a>640-R1&&a<640-L1) { p->x=a; break; } } break; case 18432: /*按向上键*/ a=(p->y)-5; if(p->lr==1) { if(a>T1&&a<B1) { p->y=a; break; } } else { if(a>T1&&a<B1) { p->y=a; break; } } break; case 20480: /*按向下键*/ a=(p->y)+5; if(a>T1&&a<B1) { p->y=a; } break; case 7181: /*enter键的扫描码*/ if(b==1) p->lr=3; q=0; break; case 283: return 0; } } RenPicture(p->x,p->y,p->color); return 1; } /*游戏开始前画面*/ int GameStar()/*返回1表示单人游戏初级,2表示单人游戏级,3表示单人游戏高级,4表示两人对战,5表示退出游戏*/ { int q,k,h=0; for(;1;) { q=1; cleardevice();/*清屏函数*/ setcolor(15); settextstyle(0,0,5); outtextxy(100,100,"Start Game!"); settextstyle(0,0,1); outtextxy(20,300,"keys used:"); outtextxy(20,300," Arrow keys"); outtextxy(20,310," The left mouse button"); outtextxy(20,320," Enter"); outtextxy(20,330," Esc to Quit!"); setcolor(5); outtextxy(250,400,"One player!"); outtextxy(250,420,"Two players!"); outtextxy(250,440,"Quit!"); setwritemode(1); setcolor(6); rectangle(245,395+h*20,345,415+h*20); for(;q;) { setcolor(6); k=bioskey(0); sound(1000);/*响声函数*/ delay(10000); nosound(); if(k==20480) { rectangle(245,395+h*20,345,415+h*20); h=(h+1)%3; rectangle(245,395+h*20,345,415+h*20); }else if(k==7181) { if(h==0)/*单人游戏,选择等级*/ { cleardevice();/*清屏函数*/ setcolor(2); outtextxy(20,30," Esc to back!"); outtextxy(250,240,"Lower"); outtextxy(250,260,"Middle"); outtextxy(250,280,"Higher"); setcolor(4); rectangle(245,235+h*20,300,255+h*20); for(;q;) { k=bioskey(0); sound(1000);/*响声函数*/ delay(10000); nosound(); if(k==20480) { rectangle(245,235+h*20,300,255+h*20); h=(h+1)%3; rectangle(245,235+h*20,300,255+h*20); }else if(k==7181) { return h+1; }else if(k==283) { h=0; k=1; q=0; break; }else{} } } if(h==1)/*两人对抗*/ return 4; if(h==2)/*退出游戏*/ return 5; }else if(k==283) { return 5; }else {} } } } /*退出游戏画面*/ void GameOver() { cleardevice();/*清屏函数*/ setcolor(14); settextstyle(0,0,6); outtextxy(100,200,"Game Over!"); settextstyle(1,0,1); outtextxy(400,400,"Producer:ChenChen"); outtextxy(400,410," QQ:804620957"); outtextxy(400,420," Time:2010.5.28"); } /*主函数*/ void main() { int gd=DETECT,gm; int q=0,schoose=1; int out=1; int pmc=1; int cla2s=1; struct Ren ren1,ren2; initgraph(&gd;,&gm;,""); /* registerbgidriver(EGAVGA_driver);*/ cleardevice();/*清屏函数*/ MouseMath();/*计算鼠标形状,一开始必须使用,后面就不用了*/ MouseSetY(0,479); MouseSetX(0,649); MouseSetXY(100,100); for(;out;) { pmc=GameStar(); cleardevice();/*清屏函数*/ settextstyle(1,0,1);/*初始化*/ schoose=1; ren2.x=540;ren2.y=320;ren2.life=200;ren2.color=3;ren2.lr=2; if(pmc<4) { ren1.x=640-ren2.x;ren1.y=ren2.y;ren1.life=ren2.life;ren1.color=2;ren1.lr=3; cla2s=pmc; }else if(pmc==4) { ren1.x=640-ren2.x;ren1.y=ren2.y;ren1.life=ren2.life;ren1.color=2;ren1.lr=1; }else { break;} Desktop(); AngleSpeed(0,0); RenPicture(ren1.x,ren1.y,ren1.color); RenPicture(ren2.x,ren2.y,ren2.color); LifePicture(ren1.life,ren1.color,ren1.lr); LifePicture(ren2.life,ren2.color,ren2.lr); for(;ren1.life>0&&ren2;.life>0;schoose++) { if(schoose%2) { RenPicture(ren1.x,ren1.y,ren1.color); if(MoveRen(&ren1;)==0) break; q=Launch(ren1.x,ren1.y,ren2.x,ren2.y,ren1.lr,cla2s); if(q==1) ren2.life=ren2.life-40; if(q==2) ren2.life=ren2.life-20; if(q==3) ren2.life=ren2.life-10; if(ren2.life<0) ren2.life=0; LifePicture(ren2.life,ren2.color,ren2.lr); } else { RenPicture(ren2.x,ren2.y,ren2.color); if(MoveRen(&ren2;)==0) break; q=Launch(ren2.x,ren2.y,ren1.x,ren1.y,ren2.lr,cla2s); if(q==1) ren1.life=ren1.life-40; if(q==2) ren1.life=ren1.life-20; if(q==3) ren1.life=ren1.life-10; if(ren1.life<0) ren1.life=0; LifePicture(ren1.life,ren1.color,ren1.lr); } } if(ren1.life<ren2.life) { settextstyle(0,0,6); setcolor(ren2.color); outtextxy(150,280,"P2 win!"); settextstyle(1,0,1); } else if(ren1.life>ren2.life) { settextstyle(0,0,6); setcolor(ren1.color); outtextxy(150,280,"P1 win!"); settextstyle(1,0,1); } else { settextstyle(0,0,6); setcolor(15); outtextxy(150,280,"Drew!"); settextstyle(1,0,1); } getch(); } GameOver(); getch(); closegraph(); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼月半

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值