举例说明类 直接初始化VS复制初始化【未完待续】

来源:互联网 发布:重庆时时开奖软件 编辑:程序博客网 时间:2024/06/04 18:56

int a(5); //直接初始化

int a=5; //复制初始化

(1)对于一般的内建类型,这两种初始化基本上没有区别。 

(2)当用于类类型对象时,初始化的复制形式和直接形式有所不同:

直接初始化直接调用与实参匹配的构造函数(拷贝构造函数)

复制初始化首先使用指定构造函数创建一个临时对象,然后使用复制构造函数将那个临时对象复制到正在创建的对象。 


#include "stdafx.h"

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


class Test
{
public:
Test(){}
Test(int m,int n){a=m;b=n;}
Test(const Test& A){a=A.a;b=A.b;}
private:
int a,b;
};


class Matrix
{
public:
Matrix(int m,int n, const Test& p) //通过设置断点,发现:如果构造函数没有初始化列表,走Test的默认构造函数
{
a=m;
b=n;
test=p;

}

/*

Matrix(int m,int n, const Test& p):a(m),b(n),test(p){}// 走拷贝构造函数

*/

Matrix(){}
private:
int a,b;
Test test;
};


int  main(int argc,  char* argv[])
{
Test C(6,7);
Matrix A(1,3,C);


system("pause");
return 0;
}
0 0