当前位置:编程学习 > C/C++ >>

类函数指针和普通函数指针

我们都看惯了一般的函数指针,但是关于类的函数指针又是怎样的呢?它的静态函数指针和非静态函数指针是一样的么?
 
 
 
<span style="font-size:18px">#include<iostream>  
using namespace std;  
  
  
typedef int(*pMax)(int,int);//普通函数指针  
  
  
int max(int a,int b)  
{  
<span style="white-space:pre">  </span>return a>b?a:b;  
}  
  
  
class A  
{  
public:  
<span style="white-space:pre">  </span>int min(int a,int b)  
<span style="white-space:pre">  </span>{  
<span style="white-space:pre">      </span>return a<b?a:b;  
<span style="white-space:pre">  </span>}  
  
  
<span style="white-space:pre">  </span>static int myMin(int a,int b)  
<span style="white-space:pre">  </span>{  
<span style="white-space:pre">      </span>return a<b?a:b;  
<span style="white-space:pre">  </span>}  
};  
  
  
class B:public A  
{  
  
  
};  
typedef int (A::*pMin)(int,int);//类的非静态函数指针  
typedef int (*pMyMin)(int,int);//类的静态函数指针  
  
  
typedef int (B::*pMinB)(int,int);//类的非静态函数指针  
  
  
void main()  
{  
<span style="white-space:pre">  </span>int a=3;  
<span style="white-space:pre">  </span>int b=4;  
<span style="white-space:pre">  </span>  
<span style="white-space:pre">  </span>cout<<max(a,b)<<endl;  
<span style="white-space:pre">  </span>/*    测试普通函数指针    */  
<span style="white-space:pre">  </span>pMax p1=&max;  
<span style="white-space:pre">  </span>cout<<(*p1)(a,b)<<endl;  
  
  
<span style="white-space:pre">  </span>int (*p2)(int, int)=&max;  
<span style="white-space:pre">  </span>cout<<(*p2)(a,b)<<endl;  
  
  
<span style="white-space:pre">  </span>/*    测试类的非静态函数指针    */  
<span style="white-space:pre">  </span>A TestA;  
<span style="white-space:pre">  </span>pMin p3=&A::min;  
<span style="white-space:pre">  </span>cout<<(TestA.*p3)(a,b)<<endl;  
  
  
<span style="white-space:pre">  </span>int(A::*p4)(int,int)=&A::min;  
<span style="white-space:pre">  </span>cout<<(TestA.*p4)(a,b)<<endl;  
<span style="white-space:pre">  </span>  
  
  
<span style="white-space:pre">  </span>/*    测试类的静态函数指针    */  
<span style="white-space:pre">  </span>pMyMin p5=&A::myMin;  
<span style="white-space:pre">  </span>cout<<(*p5)(a,b)<<endl;  
  
  
<span style="white-space:pre">  </span>int(*p6)(int,int)=&A::myMin;  
<span style="white-space:pre">  </span>cout<<(*p6)(a,b)<<endl;  
  
  
  
  
<span style="white-space:pre">  </span>/*    测试非静态函数指针在类继承中怎么使用    */  
<span style="white-space:pre">  </span>B TestB;  
<span style="white-space:pre">  </span>pMinB p7=&A::min;  
  
  
<span style="white-space:pre">  </span>cout<<(TestB.*p7)(a,b)<<endl;  
<span style="white-space:pre">  </span>cout<<(TestB.*p3)(a,b)<<endl;  
//<span style="white-space:pre">    </span>cout<<(TestA.*p7)(a,b)<<endl;错误  
}</span>  

 

 
从中可以看出,父类对象不可以调用以子类声明的函数指针,而子类对象可以调用以父类声明的函数指针。
 
 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,