WaterWalk wrote:
(I posted this topic yesterday, but it disappeared. I don't know why,
so I re-post it here)
Hello. I am rather confused about class data member pointers. Take the
following class as an example:
class MyClass
{
public:
int n;
};
I can use the data member pointer syntax to access MyClass::n:
typedef int MyClass*pn_t;
typedef int MyClass::*pn_t; // you seem to have lost the colons
pn_t pn = &MyClass::n;
MyClass my;
pn = &my.n;
*pn = 123;
This is not a valid syntax. You need to specify the instance of the
class _explicitly_, even if it's a 'this':
this->*pn = 123;
or, in your case it MUST be
my.*pn = 123;
You may be using some kind of compiler extension. If that's the case,
make sure to disable compiler extensions during learning.
But at the same time, I can also just use a common data pointer:
MyClass my;
int *pn = &my.n;
*pn = 123;
I don't know if the second method is legal in the c++ standard. If it
is, why bother to have the first method?
Pointers to members have use when you need to manipulate a certain
member of the class but the instance is not known until some time later.
In your case, 'my' is the instance, and it's known before you even take
the address of 'n'. What if you have to decide later? This example is
somewhat contrived, but still
struct Foo
{
int a, b;
};
void set_member(Foo& foo, int Foo::*which_member)
{
foo.*which_member = 42;
}
int main(int argc, char *argv[])
{
Foo f1, f2;
if (argc & 1 == 0) // 2, 4, etc.
{
if (*argv[1] == 'a')
set_member(f1, &Foo::a);
if (*argv[1] == 'b')
set_member(f1, &Foo::b);
}
else
{
if (argv[0][1] == 'u')
set_member(f2, &Foo::a);
if (argv[0][1] == 's')
set_member(f2, &Foo::b);
}
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask