C++中面向对象模型即类的封装原理初探
这里主要概述成员函数的本质,这里只是用C语言的方式来实现C++中类的功能,并不代表C++编译器的真正做法,但C++编译器实现原理大致如此。
/*注释部分为c代码的实现方式,也是C++编译器的实现原理*/
#include <iostream>
#include <cstdlib>
using namespace std;
class Test
{
private:
int mI;
public:
Test(int i)
{
mI = i;
}
int getI()
{
return mI;
}
static void print()
{
printf("This is class Test. \n");
}
};
/**********************
struct Test
{
int mI;
};
void Test_initialize(Test * pThis, int i)
{
pThis->mI = i;
}
int Test_getI(Test * pThis)
{
return pThis->mI;
}
void Test_Print()
{
printf("This is class Test.\n");
}
***********************/
int main()
{
Test a(10);
/*
Test a;
Test_initialize(&a, 10);
*/
a.getI();
/*
Test_getI(&a);
*/
Test::print();
/*
Test_Print();
*/
system("pause");
return 0;
}
总结:
1、C++类对象中的成员变量和成员函数是分开存储的,C语言的内存四区模型仍然有效;
2、C++中类的普通成员函数都隐式包含一个指向当前对象的this指针;
3、静态成员函数、成员变量属于类
静态成员函数与普通成员函数的区别在于
静态成员函数不包含指向具体对象的指针
普通成员函数包含一个指向具体对象的指针。
这一点可以在普通成员函数的函数指针和静态成员函数的函数指针类型声明中体现:
#include <iostream>
class Test
{
public:
Test(int a, int b): a(a), b(b)
{}
static void print (Test & test)
{
std::cout << test.a << std::endl;
std::cout << test.b << std::endl;
}
void output ()
{
std::cout << this->a << std::endl;
std::cout << this->b << std::endl;
}
private:
int a;
int b;
};
int main()
{
Test test(1, 2);
typedef void(Test::* MemFun)();//普通成员函数的函数指针定义
MemFun output = &Test::output;
(test.*output)();
typedef void(* StaticMemFun)(Test&);//静态成员函数的函数指针定义
StaticMemFun print = &Test::print;
print(test);
}
上述代码中,普通成员函数函数指针类型*前要加"类名::",而静态成员函数不需要,这是由于普通成员函数隐含传递this指针作为其第一个参数,而静态成员函数不传递this指针,所以静态成员函数的指针类型和和类外的单独函数指针没有区别。
类成员函数指针的具体分析请参见以下链接: