Chinaunix首页 | 论坛 | 博客
  • 博客访问: 65837
  • 博文数量: 42
  • 博客积分: 1730
  • 博客等级: 上尉
  • 技术积分: 430
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-02 13:06
文章分类

全部博文(42)

文章存档

2011年(1)

2009年(41)

我的朋友

分类: C/C++

2009-11-24 20:45:41

// Construct.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
using namespace std;
class Value
{
public:
 Value(int d=1)
 {
  for (int i=0;i<1000;i++)
  {
   v[i] = d+i;
  }
 }
 void init(int d=1)
 {
  for (int i=0;i<1000;i++)
  {
   v[i] = d+i;
  }
 }
private:
 int v[1000];
};
class Object
{
public:
/////////////1////////////
//  Object(int d):val(d)
//  {
//
//  }
/////////////1////////////
/////////////2////////////
 Object(int d)
 {
  val.init(d);
 }
/////////////2////////////
private:
 Value val;
};
int _tmain(int argc, _TCHAR* argv[])
{
 int count;
 count = GetTickCount();
 for (int i=0;i<100000;i++)
 {
  Object obj(2);
 }
 count=GetTickCount()-count;
 cout< return 0;
}
/*
为什么使用1和2两种不同的构造函数,运行的时间有那么大的差距,2的运行时间差不多是1的两倍
在我的机器上1的时间是313 2的时间是625
原来构造函数中蕴含了很多的奥秘:
首先在构造函数中,在执行函数体之前(注意)还有很多隐藏的操作
如果有初始化列表,则先执行初始化列表,再进入执行构造函数体
对于没有在初始化列表中出现的类成员,也会执行默认的构造函数
即所有的成员变量在执行构造函数体之前已经有了初始值,这也就是为什么常量型或者引用型的变量
的初始化必须放在初始化列表里。而对于类成员变量放在初始化列表是为了减少不必要的重复赋值
*/
阅读(370) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~