3

I have to make a member data pointer to get less copy of the data.I have writed some sample code.Some error occurred where I marked "error". How to do rightly.

#include <iostream>

class A {
public:
    A() {
        stra="12345";
    }
    virtual ~A() {}
    string stra;
}

class B {
public:
    B(A *pt) {
        strb=&(pt->stra);  //Error.An assignment statement
    }
    virtual ~B() {}
    string A::*strb;       //member data pointer from class A
}

int main() {
    A ma;
    B mb(&ma);
    std::cout<< *(mb.strb) <<std::endl;  //Error.print data
}
simon
  • 569
  • 9
  • 20

2 Answers2

2

In effect, what you have is a standard pointer, not a pointer-to-member. The following will work:

#include <iostream>
#include <string>

using namespace std;


class A {
public:
    A() {
        stra="12345";
    }
    virtual ~A() {}
    string stra;
};

class B {
public:
    B(A *pt) {
        strb=&(pt->stra);
    }
    virtual ~B() {}
    string* strb; // <<<<<<<< THIS
};

int main() {
    A ma;
    B mb(&ma);
    std::cout<< *(mb.strb) <<std::endl;
}

For some discussion on pointers to data members, see C++: Pointer to class data member

I don't know where you're going with all this, but having instances of one class keep pointers to things inside instances of another class strikes me as a rather poor design.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • In the beginning I do so, but there is an error.You are correct, it appears that an error in another place.Thank you. – simon Dec 01 '12 at 08:55
0

string A::*strb; should be string* strb;

B should have a pointer to a string object, not a pointer to an A string(?)

Alan
  • 45,915
  • 17
  • 113
  • 134