Hiroki Horiuchi wrote in
news:85**************************@posting.google.c om:
Hello.
I wrote a program, but g++ warns
a.c:11: warning: invalid access to non-static data member `A::y' of
NULL object a.c:11: warning: (perhaps the `offsetof' macro was used
incorrectly)
The program is like below.
class A
{
private:
int x;
int y;
public:
static unsigned int const y_offset;
};
unsigned int const A::y_offset = (
reinterpret_cast<char *>(&static_cast<A *>(0)->y)
-
static_cast<char *>(0)
);
static_cast<A *>(0) is NULL pointer you may not dereference it any
portable way. Note the Standard says that the inbult operator ->
derefences the pointer that its applied to, so it does even though
all you do is take an address.
I want to define a constant like A::y_offset with g++ without
warnings. Is it possible?
Look into the offsetof macro and use it correctly,
#include <iostream>
#include <cstdlib>
/* struct/class must be a POD (Plain Old Data) to be
sutable for use with offsetof
*/
struct A_POD
{
int x;
int y;
int z;
};
class A : private A_POD
{
public:
int &operator [] ( unsigned off );
static unsigned int const offset[ 3 ];
A( int xx, int yy, int zz )
{
x = xx;
y = yy;
z = zz;
}
};
unsigned int const A::offset[ 3 ] =
{
offsetof( A_POD, x ),
offsetof( A_POD, y ),
offsetof( A_POD, z )
};
int & A::operator [] ( unsigned off )
{
return *reinterpret_cast< int * >(
reinterpret_cast< char * >(
static_cast< A_POD * >( this )
)
+
offset[ off ]
);
}
int main()
{
A a( 1, 2, 3 );
std::cerr
<< a[ 0 ] << "\n"
<< a[ 1 ] << "\n"
<< a[ 2 ] << "\n"
;
}
HTH
Rob.
--
http://www.victim-prime.dsl.pipex.com/