您的位置:首页 > 编程语言 > C语言/C++

C++语言基础 例程 对象指针

2015-03-25 20:32 405 查看
贺老师的教学链接 本课讲解

示例:使用指向对象数据成员的指针
#include <iostream>
using namespace std;
class Time
{
public:
    Time(int,int,int);
    void get_time( );
private:
    int hour,minute,sec;
};
Time::Time(int h,int m,int s):hour(h),minute(m),sec(s) {}
void Time::get_time( )
{
    cout<<hour<<":"<<minute<<":" <<sec<<endl;
}
int main( )
{
    Time t(10,13,56);
    int *p1;
    p1 = &t.hour;  //这个地方有错
    cout<<*p1<<endl;
    return 0;
}

示例:使用指向对象成员函数的指针
#include <iostream>
using namespace std;
class Time
{
public:
    Time(int,int,int);
    void get_time( );
private:
    int hour,minute,sec;
};
Time::Time(int h,int m,int s):hour(h),minute(m),sec(s) {}
void Time::get_time( )
{
    cout<<hour<<":"<<minute<<":" <<sec<<endl;
}
int main( )
{
    Time t(10,13,56);
    void (Time::*p)( );
    p=&Time::get_time;    //而非p2=&t1.get_time;
    (t.*p)( );
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: