成员指针的运用续(地址与成员变量的输出)

来源:互联网 发布:淘宝网报名双11 编辑:程序博客网 时间:2024/06/06 20:34
/*

 * 如何定义结构体成员变量(类成员变量)指针?如何输出结构体成员变量(类成员变量)的地址?

 *输出结构体成员变量(类成员变量)的几种方法

 */

#include <iostream>
using namespace std;
#include <string>
struct Person
{
string name;
double salary;
int age;
};
int main()
{
Person per[2] = {{"zhou",5000,24},{"Li",7000,24}};
union{
  //这里定义的n不再是普通意义上的n(即整型的n),而是代表相对偏移地址(字节的个数)
int n;
string Person::*mn;
double Person::*ms;
int Person::*ma;
};
mn = &Person::name;
cout << n << endl;
ms = &Person::salary;
cout << n << endl;
ma = &Person::age;
cout << n << endl;

       //访问成员方式:结构体变量(对象).*成员指针、结构体对象.成员、结构体对象指针->*成员指针(成员)

int i;
//方式一:结构体对象.成员
        /*for(i = 0; i != 2; i++)
{
cout << per[i].name << ',' << per[i].salary << ',' << per[i].age;
cout << endl;
}*/
//方式二:结构体对象.*成员指针
string Person::*pn = &Person::name;
double Person::*ps = &Person::salary;
int Person::*pa = &Person::age;
/*for(i = 0; i != 2; i++)
{
cout << per[i].*pn << ',' << per[i].*ps << ',' << per[i].*pa;
cout << endl;
}*/
//方式三:结构体对象指针->成员
Person* op = per;
/*for(i = 0; i != 2; i++)
{
cout << (op+i)->name << ',' << (op+i)->salary << ',' << (op+i)->age;
cout << endl;
}*/
//方式四:结构体对象指针->*成员指针
for(i = 0; i != 2; i++)
{
cout << (op+i)->*pn << ',' << (op+i)->*ps << ',' << (op+i)->*pa;
cout << endl;
}
return 0;
}
原创粉丝点击