简体   繁体   中英

Accessing class members that are arrays through “pointers to class members”

I have written below code to explore pointers to class members:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class Sample{
    public:
        int i;
        char name[35];
        char* City;

        Sample(int i,const char* ptr,const char* addr):i(i){
            strncpy(name,ptr,35);
            City= (char*) malloc(strlen(addr)*sizeof(char));
            strcpy(City,addr);
        }
};

int main()
{
    Sample Ob1(1,"Andrew Thomas","Glasgow");
    cout << Ob1.i << " : " << Ob1.name << " lives at : "<< (Ob1.City)<< endl;
    int Sample::*FI=&Sample::i;
    char* Sample::*FCity= &Sample::City;
    char* Sample::*FName=  &Sample::name;

    cout << Ob1.*FI << endl;
    cout << Ob1.*FCity << endl;
    cout << Ob1.*FName << endl;

    return 0;
}

I am getting error for char* Sample::*FName= &Sample::name; as below:

$ g++ -Wall ExploreGDB.cpp -o ExploreGDB
ExploreGDB.cpp: In function ‘int main()’:
ExploreGDB.cpp:28:34: error: cannot convert ‘char (Sample::*)[35]’ to ‘char* Sample::*’ in initialization
  char* Sample::*FName=  &Sample::name;
                                  ^

The rest of the code works fine.

Can anyone let me know how to declare a pointer to data member declared as - char name[35]; ?

You need to declare the pointer as follows:

char (Sample::*FName)[35]=  &Sample::name;

The general rule is that U (T::*<var_name>) declares pointer to a member of class T with type U . Here, the type is char <var_name>[35] , so the syntax above is required.

Also note, your malloc is incorrect. strlen gives the number of characters in the string, but to represent that, you need one more character for the terminating null char:

City= (char*) malloc(strlen(addr)+1);
strcpy(City,addr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM