Ich bin ein Zeichen!

News
TODO
Projekte
Mobile Stromversorgung
Primzahlen berechnen
Laser Versuche
LED Lampe
Solarzellen
Unterm Tisch Beleuchtung
avrgcc installieren
Lichterkette
FHR
Elektrozünder
fnordlicht
Böses Internet...
LED Matrix
getPrivateVariables
wardrive
aboutyou
Lyric
Quit Message
Links
Temperatur
ICQ ...
Muell
Unix
Meine Bücher
Murphy's Law
Zaurus
Hostnames
U23
How to read/write private or protected variables without get/set-methods
Jaa, man darf in Objekt Orientiete Sprachen ja nicht auf geschützt Variablen oder Funktionen in Klassen zugreifen. Hier steht wie man dennnoch rankommt. Der Quelltext sollte gröstenteils selbsterklärend sein.
/* * How to read/write private or protected variables without get/set-methods * * If you try to access a private variable you get a compiler error like this: * * std::cout << merf->c; * getPrivetMember.cpp:87: error: `int testclass::c' is private * */ #include < iostream > class testclass { public: int a; testclass() { a = 10; b = 20; c = 30; } void show() { std::cout << "a = " << a << " b = " << b << " c = " << c << '\n'; } private: int b; protected: int c; }; int main() { testclass *merf = new testclass(); int *address = 0; std::cout << "Bytes of an int: " << sizeof(int) << "\n"; merf->show(); std::cout << "a = " << merf->a << '\n'; // read the variables address = (int*) &merf->a; std::cout << "read the variables...\n=====================\n"; std::cout << "address of a = " << &merf->a << '\n'; std::cout << "value of a = " << *address << '\n'; address += 1; std::cout << "address + 1 = " << address << '\n'; std::cout << "value of b = " << *address << '\n'; address += 1; std::cout << "address + 2 = " << address << '\n'; std::cout << "value of c = " << *address << '\n'; // write to the variables address = (int*) &merf->a; std::cout << "write to the variables\n======================\n"; *address = 50; std::cout << "set value of a to = " << *address << '\n'; address += 1; *address = 100; std::cout << "set value of b to = " << *address << '\n'; address += 1; *address = 200; std::cout << "set value of a to = " << *address << '\n'; merf->show(); delete merf; return 0; }