成员指针的定义与简单应用(成员变量地址的问题)

/*
 * 成员指针的一些问题
 * 成员指针可以让我们能够访问数据成员中的某一单独的成员
 * 成员指针的定义:
 * ElemType struct_name::*mp;
 */
#include <iostream>
using namespace std;

#include <string>

struct Student
{
int NumID;
int age;
int height;
void Output();
};

//访问成员方式:结构体变量(对象).*成员指针、结构体对象.成员、结构体对象指针->*成员指针(成员)
void showmember(Student* stt,int n,int Student::*mp)
{
for(int i = 0; i != n; i++)
cout << (stt+i)->*mp << ','; //cout << stt[i].*mp << ',';
cout << endl;
}
int main()
{
Student stu[3] = {{1001,23,165},{1002,24,172},{1003,23,168}};
Student st = {1004,23,167};
for(int i = 0; i != 3; i++)
cout << "&stu[" << i << "]=" << &stu[i] << endl;
cout << endl;
cout << "&st=" << &st << endl;  //对象的地址
cout << "st.NumID=" << st.NumID << ','\
    << "st.age=" << st.age << ','\
    << "st.height=" << st.height << endl; 
cout << "&st.NumID =" << &st.NumID << endl;  //对象成员的地址
cout << "&st.age   =" << &st.age << endl;
cout << "&st.height=" << &st.height << endl; 

//如果不定义结构体对象,而想直接输出成员变量的地址怎么做???
/*在C++中,函数的地址、成员的地址,如果输出的话,其值为true,即为 1;一般是不输出的。
 如下输出,得到的结果都会是 true(1) 。*/
cout << &Student::NumID << ',' << &Student::age << ',' << &Student::height << endl;
//cout << &main << endl;
//但是,如果非要输出的话,可以采用联合(union),而且是匿名联合
union{
int num;
int Student::*mp;  //成员指针
};
/*用struct定义的结构体是抽象类型,不会占有内存空间,只有在定义了具体的结构体对象
 之后,系统才会给具体的对象分配内存空间;因此,对于抽象的结构体它是不会有地址的。
 并且,结构体对象和结构体对象的第一个数据成员的地址是相同的,但是它们的意义完全不同。*/

/*对于采用联合,在其中定义成员指针,指向结构体的数据成员,可以得到结构体成员
 的相对地址(相对与结构体的偏移地址)。*/
//下面所求得就是相对地址
mp = &Student::NumID;
cout << "n=" << num << endl;
mp = &Student::age;
cout << "n=" << num << endl;
mp = &Student::height;
cout << "n=" << num << endl;

showmember(stu,3,&Student::NumID);
showmember(stu,3,&Student::age);
showmember(stu,3,&Student::height);

//showmember(&st,1,&Student::NumID);
//showmember(&st,1,&Student::age);
//showmember(&st,1,&Student::height);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值