c++对象指针实例
1、#include<iostream>
using namespace std;
class Time
{
public:
Time(int,int,int);//声明结构函数
int hour;
int minute;
int sec;
void get_time();//声明公有成员函数
};

2、Time::Time(int h,int m,int s)//在类外定义结构函数
{
hour=h;
minute=m;
sec=s;
}

3、void Time::get_time()//在类外定义公有成员函数
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}

4、int main()
{
Time t1(10,10,10);//定义Time 类对象t1,并且对其初始化
int *p1=&t1.hour;//在这里,hour,minute,sec是公有的所以可以直接使用,如果这些变量在类里面是私有的,必须在类当中建立一个接口(成员函数)来调用私有数据成员(在下面为大家展示)
cout<<*p1<<endl;//输出p1所指的数据成员t.hour
t1.get_time(); //调用对象t1的公用成员函数get_time()
Time *p2=&t1; //定义指向Time类对象的指针p2,并且使p2指向t1;
p2->get_time();
void(Time::*p3)();//定义指向Time类公用成员函数的指针p3,使用模板:数据类型名(类名::指针变量名)(参数列表);
p3=&Time::get_time;//使p3指向get_time函数
(t1.*p3)();//调用p3所指的成员函数
return 0;
}


5、使用私有成员数据:
#include<iostream>
using namespace std;
class Time
{
public:
Time(int h=0,int m=0,int s=0);
int GetHour()
{
return hour;
}
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
Time::Time(int h,int m,int s)
{
hour=h;
minute=h;
sec=s;
}
void Time::set_time()
{
cin>>hour>>minute>>sec;
}
void Time::show_time()
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main()
{
Time t1;
int d=t1.GetHour();//首先必须将返回值传递给一个变量(如何通过指针访问 //私有数据成员,需要在上面开一个接口)
int *p1=&d; //然后将变量的地址赋给指针p
//注意:不能直接这样,int *p1=&t1.GetHour;
cout<<*p1<<endl;
Time t2;
t1.set_time();
t1.show_time();
Time *p2=&t1; //指向对象的指针
p2->show_time();
void(Time::*p3)(); //定义指向公用成员函数的指针
p3=&Time::show_time;//使指针指向一个公用函数
(t1.*p3)(); //调用对象t1中p3所指的成员函数
return 0;
}