简体   繁体   English

通过“指向类成员的指针”访问作为数组的类成员

[英]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; 我收到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]; 谁能让我知道如何声明一个指向声明为char name[35];数据成员的指针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 . 一般规则是U (T::*<var_name>)声明指向类型为U的类T的成员的指针。 Here, the type is char <var_name>[35] , so the syntax above is required. 在这里,类型为char <var_name>[35] ,因此需要以上语法。

Also note, your malloc is incorrect. 另请注意,您的malloc不正确。 strlen gives the number of characters in the string, but to represent that, you need one more character for the terminating null char: strlen给出了字符串中的字符数,但要表示该数字,您还需要一个字符来结束空字符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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