C
Meep Meep schrieb:
hola
hab folgenden source mal gefunden, is zwar urhaesslich, funkt aber. zumindest beim bcb:
// h-file
class ChangeConst
{
private:
int a;
char t;
const int b;
int c;
public:
ChangeConst(void);
~ChangeConst(void);
void change_once(int zahl);
int GetB(void) { return b; }
};
// cpp-file
ChangeConst::ChangeConst(void) : a(0), b(0), c(0)
{
// do something
}
ChangeConst::~ChangeConst(void)
{
// do something
}
void ChangeConst::change_once(int zahl)
{
if(!b)
{
const int *p = &b;
int this_address = (int)this;
int b_address = (int)p;
int offset = b_address - this_address;
if(offset & 0x3)
this_address += offset & 0x3;
int *q = (int*)this_address;
*(q + (offset >> 2)) = zahl;
}
}
Meep Meep
dann kannst du genausogut const_cast verwenden, dass ist portabel, effizienter und man sieht wenigstens, was passiert.
template < class T > class ChangeOnce
{
public:
ChangeOnce(T const& initialValue = T() )
: v( initialValue ), changed( false )
{ }
ChangeOnce(ChangeOnce<T> const& rhs)
: v( rhs.v ), changed( false )
{ }
ChangeOnce<T> const& operator=(ChangeOnce<T> const& rhs)
{
return *this = rhs.v;
}
ChangeOnce<T> const& operator=(T const& rhs)
// kann nur einmal ändern, daher reference to const als returntyp
{
if( changed ) throw std::exception();
v = rhs;
changed = true;
return *this;
}
operator T() const { return v; }
private:
T v;
bool changed;
};