C++中变量的构造顺序

①设定静态数据成员初始化时,不受任何存取权限的束缚。

②每个类中,不论有多少个虚函数,都只有一个vptr指向虚函数表。

③类的定义也存在内存对齐问题,且sizeof不计入static变量。

#include<iostream>
using namespace std;

class A
{
private:
	char ch1;
	char ch2;
	int a;
	static double dd;
};

class B
{
private:
	char ch1;
	int a;
	char ch2;
	static double dd;
static double ddd;
};

int main()
{
	A a;
    B b ;
	cout << "sizeof (a ) = " << sizeof( a ) << "\n" << "sizeof( b)= " <<  sizeof( b ) << endl;
	return 0;
}
以上运行答案是:sizeof ( a ) = 8  sizeof( b ) = 12;

4)构造函数与析构函数

#include<iostream>
#include<string.h>
using namespace std;

class CDemo
{
public:
	CDemo( const char * str);
	~CDemo();
private:
	char name[20];
};
CDemo::CDemo(const char * str)
{
	strncpy( name , str, 20);
	cout << "Constructor called for " << name << endl;
}

CDemo::~CDemo()
{
	cout << "Destructor called of " << name << endl;
}

void func()
{
	CDemo LocalObjectInFunc( "LocalObjectInFunc");
	static CDemo StaticObject( "StaticObject");
	CDemo *pHeapObjectInFunc = new CDemo( "HeapObjectInFunc");
	cout << "Inside func" << endl;
}


CDemo GlobalObject( "GlobalObject");

void main()
{
	CDemo LocalObjectInMain("LocalObjectInMain");
	CDemo* pHeapObjectInMain = new CDemo("HeapObjectInMain");

	cout << "In main , before calling func"<< endl;
	func();
	cout << " In main, after calling func" << endl;
}


有几点需要注意的地方:

1.全局对象的构造函数最先执行,比程序进入点更早,且其析构函数在程序即将结束前执行。

2.对于局部对象,当对象诞生时,其构造函数被执行,当程序流程即将离开该对象的活动范围时,其析构函数给执行

3.对于静态对象,当对象诞生时其构造函数被执行,当程序将结束时,其析构函数被执行。但比全局对象的析构函数更早一步。

4.对于以New方式产生出来的局部对象,当对象诞生时其构造函数被执行,析构函数则在对象被delete时执行。



你可能感兴趣的:(C++,delete,Class,mfc,Constructor,destructor)