class私有變量

在C++中私有成員變量是不能在作用域外賦值的,這是C++語法和語義上做了限制,但是C++是在C基礎上發展而來,class跟struct是沒有區別。現在我介紹一種C++私有變量另類賦值方法,荒淫大家拍磚。

#include <iostream>
#include <cstdio>
#include <conio.h>
using namespace std;
class Foo
{
	char a;            //偏移量 0
	int b;
public:
	void show(){ cout<<"a="<<a<<" "<<"b="<<b<<endl;}
};
int main()
{
	Foo foo;
	char *p1 = 0;   
	int *p2 = 0;
	p1 = (char*)&foo+0;
	p2 = (int*)&foo+1;

	*p1 = 'a';
	*p2 = 10;
	foo.show ();
	_getch();
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章