您的位置:首页 > 编程语言 > C语言/C++

C++ class与内存

2015-08-09 16:43 543 查看
//类名 变量名 栈区

//类名 *指针名 = new 类名 堆区

//类的静态成员 静态区

//类的成员函数,静态函数都在代码区,类的函数都是共享的

//代码共享,所有的类对象共享代码

//const变量在类的外部,一开始必须初始化,用常量强行替换,不读内存

//const变量在类的内部,必须构建一个类才能初始化,const与C语言里的const是一样的

//常规创建类对象的时候在栈上,new创建对象的时候,在堆上

//引用本质上就是变量的别名,4个字节,本质上是一个指针

//引用变量跟其他变量一样,常规创建类对象的时候在栈上,new创建对象的时候,在堆上

//static const int dashu;//静态常量区

//静态常量区可以访问,但是不能修改,可以用注射的方式修改

#include <iostream>
#include <functional>
using namespace std;
using namespace placeholders;
class myclass
{
public:
int num;
int data;
int *p;
const int coint;
int &myint;
static int shu;
static const int dashu;//静态常量区
public:
static void go()
{
cout << "hehehe" << endl;
}
void run()
{
cout << "runrunrun" << endl;
}
myclass(int a, int b) :coint(a), myint(b)
{
cout << &a << "  " << &b << endl;
cout << &coint << "  " << &myint << endl;
const int *p = &coint;
cout << *p << "  " << coint << endl;
int *px = const_cast<int*>(p);
*px = 12;
cout << coint << "  " << *px << endl;
}
~myclass()
{

}
};
int myclass::shu = 0;//初始化
const int myclass::dashu = 20;
void main()
{
myclass myclass1(10,9);

void(myclass::*p)() = &myclass::run;//传统函数指针调用,代码共享,所有的类对象共享代码

void(*p1)() = &myclass::go;//函数指针调用静态函数,go

auto func1 = bind(&myclass::run, &myclass1);//仿函数调用run
func1();

const int *px = &myclass::dashu;
int *ppx = const_cast<int*>(px);
*ppx = 12;//静态常量区可以访问,但是不能修改,可以用注射的方式修改
cout << *ppx << "  " << *px << "  " << myclass::dashu << endl;

cin.get();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class 内存 c++基础