成員指針的定義與簡單應用(成員變量地址的問題)

/*
 * 成員指針的一些問題
 * 成員指針可以讓我們能夠訪問數據成員中的某一單獨的成員
 * 成員指針的定義:
 * 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章