C++成员函数的本质:

 

如下一段代码,类A有两个成员变量xy,一个构造函数,一个成员函数show

#include<iostream>
using namespace std;
class A
{
public:
   int x;
   int y;
   A(int a=0,int b=0);
   int show(int a,char* str);
};
 
int A::show(int a,char* str)
{
   cout<<str<<":\t"<<a<<endl;
   cout<<x<<"   "<<y<<endl;
   return a;
}
 
A::A(inta,int b)
{
   x=a;
   y=b;
}
 
int main()
{
   Aa;
   a.show(100,"yangdamao");
   cin.get();
   return 0;
}


 

这段代码很正常,属于C++的正常代码,但现在的问题是,类成员函数和普通函数到底有什么问题?有些经验的程序员就会说,类的成员函数中,隐藏了一个this指针!非常正确。

 

我们以这个程序为例,来揭秘this指针如何被隐藏的秘密!首先,为了简化我们的问题,我们对上述代码做一点处理,规定类成员函数的调用方式为_stdcall

 

代码如下:

#include<iostream>
using namespace std;
 
class A
{
public:
  int x;
  int y;
  A(int a=0,int b=0);
  int __stdcall show(int a,char* str);
};
 
int A::show(int a,char* str)
{
  cout<<str<<":\t"<<a<<endl;
  cout<<x<<"   "<<y<<endl;
  return a;
}
 
A::A(inta,int b)
{
  x=a;
  y=b;
}
 
int main()
{
  Aa;
  a.show(100,"yangdamao");
  cin.get();
  return 0;
}


 

在很多地方,对类成员函数的本质都有解释,我这里就不在赘述,以A::show类成员函数为例,其真正原型如下:

                   int show(A* This,int a,char* str);

 

下面一段代码证明了这个问题:

#include<iostream>
using namespace std;
 
class A
{
public:
   int x;
   int y;
   A(int a=0,int b=0);
   int __stdcall show(int a,char* str);
};
 
int A::show(int a,char* str)
{
   cout<<str<<":\t"<<a<<endl;
   cout<<x<<"   "<<y<<endl;
   return a;
}
 
A::A(inta,int b)
{
   x=a;
   y=b;
}
 
typedef int (__stdcall A::*FUN)(int,char*);
 
union U
{
   FUNfun;
   int (__stdcall*fun1)(A*,int,char*);
};
 
 
int main()
{
   Aa;
   Uu;
   u.fun=&A::show;
   u.fun1(&a,200,"zhongguoren");
   cin.get();
   return 0;
}


 

注意这段代码中的联合体U,其成员fun是类的成员函数指针,而fun1是一个普通的函数指针!(注意联合体的本质!!!如果不明白的,可以参考本人的C语言视频:)

 

你可以通过单步断点调试发现,u.fun1(&a,200,"zhongguoren");这个语句,调用的就是类A的成员函数!!

 

总结:

       类的成员函数其实没有什么神秘的,只是编译器在预处理阶段或者编译阶段,对类成员函数进行了替换,替换成普通的函数。类的每个实例,都有自己一份成员变量的拷贝,但类的成员函数,只有一个拷贝(无论有多少类实例)。