Pages

Thursday, July 23, 2009

C++ классы: размещение в памяти. Часть III.

А эта программа меняет закрытые переменные класса:

#include <stdio.h>
class C1Int
{
int x;
public:
void out_x()
{
printf("x = %d\r\n", x);
}
};
int main()
{
C1Int one_int;
printf("size of C1Int object is %d\r\n", sizeof(one_int));
int* pInt = (int*)&one_int;
*pInt = 123456789;
one_int.out_x();
printf("object as integer %d\r\n", one_int);
return 0;
}



Можна и строку поменять:

#include <windows.h>
#include <stdio.h>
class C1Char
{
char x[24];
public:
C1Char()
{
strcpy(x, "hello");
}
void out_x()
{
printf("x = %s\r\n", x);
}
};
int main()
{
C1Char one;
printf("size of C1Char object is %d\r\n", sizeof(one));
one.out_x();
char* pText = (char*)&one;
strcpy(pText, "bye");
one.out_x();
return 0;
}



Вывод: класс по размеру равен сумме размеров своих переменных и в памяти объект класса это область, где расположены его члены (так уж это переводится).
И это так, пока не появляются виртуальные функции.

No comments:

Post a Comment