Reputation: 579
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
}
Upvotes: 3
Views: 85
Reputation: 500227
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.
Upvotes: 2
Reputation: 46813
string A::*strb;
should be string* strb;
B should have a pointer to a string object, not a pointer to an A string(?)
Upvotes: 0