Chinaunix首页 | 论坛 | 博客
  • 博客访问: 655705
  • 博文数量: 150
  • 博客积分: 4070
  • 博客等级: 中校
  • 技术积分: 1795
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-23 21:44
文章分类

全部博文(150)

文章存档

2012年(1)

2011年(123)

2010年(26)

分类: C/C++

2011-06-21 15:51:15

1、指向一般变量的指针
   类型 *指针变量,如:
  1. int main()
  2. {
  3.     int a = 100;
  4.     int *p = &a;
  5.     cout<<a<<endl;
  6.     cout<<*p<<endl;

  7.     return 0;
  8. }
2、函数指针
  函数返回值类型 (*fun)(函数参数列表),如:
  1. #include <iostream>
  2. #include <time.h>
  3. using namespace std;

  4. void Show(int n)
  5. {
  6.     cout<<n<<endl;
  7. }

  8. int main()
  9. {
  10.     void (*ptr)(int n);
  11.     ptr = Show;
  12.     int x = 100;
  13.     (*ptr)(x);

  14.     return 0;
  15. }
3、指向类成员的指针,分为指向成员变量的指针和指向成员函数的指针。
  1. #include <iostream>
  2. #include <time.h>
  3. using namespace std;

  4. class Base
  5. {
  6. public:
  7.     Base(int x)
  8.     {
  9.         value = x;
  10.         a = x;
  11.     }
  12.     void fun()
  13.     {
  14.         cout<<value<<endl;
  15.     }
  16.     int a;
  17. private:
  18.     int value;
  19. };

  20. int main()
  21. {
  22.     Base b(100);
  23.     int *p = &b.a; //指向成员变量的指针
  24.     cout<<*p<<endl;
  25.     cout<<b.a<<endl;
  26.     void (Base::*ptr)(); //声明指向成员函数的指针
  27.     ptr = b.fun;
  28.     (b.*ptr)(); //通过指向成员函数的指针调用函数

  29.     return 0;
  30. }
阅读(1769) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~