1、四个类型转换
http://www.cnblogs.com/chio/archive/2007/07/18/822389.html
static_cast和dynamic_cast的区别
- dynamic_cast的向下转化必须要有虚函数,
- 对于向上转化(子类->父类),两者是相同的。dynamic_cast<Base *>(&Derived)和static_cast<Base *>(&Derived)
- 对于向下转化(父类指针->子类指针),如果父类指针指向的是子类对象,那么两者相同;如果父类指针指向的是父类对象,那么static转换会不安全,dynamic_cast会返回NULL;
#include<iostream> using namespace std; class Base { public: int m_num; void fBase() { cout<<"Base is called"<<endl; } /*virtual void fBase1() { }*/ }; class Derived :public Base { public: char *m_szName[100]; void fDeviced() { cout<<"Derived is called"<<endl; } }; int main() { Base B; Derived D; Base *pb=&B; Base *pb1=&D; /*对于上行转化,dynamic_cast和static_cast是一样的,因为指针pb只会访问基类的内容*/ pb=dynamic_cast<Base *>(&D); pb=static_cast<Base *>(&D); //*以下两句话的效果是一样的,因为pb1本身指向的是派生类对象,所以转化后,pd1和pd2的访问不会越界*/ pd1=static_cast<Derived *>(pb1); pd2=dynamic_cast<Derived *>(pb1); //以下两句话的效果是不一样的,因为pb本身指向的是基类对象,所以转化后,pd1成功,但是通过pd1可以访问派生类的成员m_szName,这是不安全的 //而dynamic_cast的会使pd2变成0,即不可以访问类的成员 Derived *pd1=static_cast<Derived *>(pb); Derived *pd2=dynamic_cast<Derived *>(pb); }
2、链表冒泡排序算法
#include<stdio.h> #include<malloc.h> #define LEN sizeof(listnode) struct listnode { int data; struct listnode *next; }; listnode *Create() { listnode *head=(listnode *)malloc(LEN); head->data=0; head->next=NULL; listnode *rear=head; int x=0; int flag=1; while(flag) { scanf("%d",&x); if(x!=0) { listnode *s=(listnode *)malloc(LEN); s->data=x; rear->next=s; rear=s; } else flag=0; } rear->next=NULL; return head; } void bubblesort(listnode * head) { listnode * end, * p , * q;//end用来记录排好序的最后一个元素地址,p,q分别为前驱,后继 int temp; p=head->next; q=p->next; end=NULL; while(end!=head->next) //如果head所指结点的next成员为end,循环结束 { p=head->next;//p结点从链表头结点开始 q=p->next;//q指向p所指结点的下一个结点 while(p->next!=end) //当p->next的值为end时,表示到链尾 { if(p->data>q->data)//按照数据域从小到大排序 { temp=p->data; p->data=q->data; q->data=temp; } p=q; q=q->next; } end=p;//使end指向每次排序的q所指的结点即尾结点 } } void print(listnode *head) { listnode *p=head->next; while(p!=NULL){ printf("%d -> ",p->data); p=p->next; } printf("\n"); } int main() { listnode *head=Create(); bubblesort(head); print(head); }
3、链表的插入排序(推荐方法)
http://blog.youkuaiyun.com/chengtao_xd/article/details/8711451
4、字符串反转的优化
1、交换的地方
2、利用指针比较快