#include <iostream>
using namespace std;

class A
{ 
private:
	int x;
	int y;

public:
	A()
	{
		cout << "constructor0" << endl;
	}


	A(int xx, int yy)
	{
		cout << "constructor" << endl;

		x = xx;
		y = yy;
	}

	void print()
	{
		cout << x << "," << y << endl;
	}
};

int main()
{
	A a1(1, 2); // 初始化

	A(3, 4).print();    // 临时对象
	
	A a2;       // 没有指定参数
	a2.print(); 
	
	A a3 = A(5, 6); // 这里只有一个对象啊, 所以只调用一次构造函数


	A m[4] = {A(7, 8), A(9, 10), A(11, 12)};  // 调用构造函数4次, 而不是8次


	int size = sizeof(m) / sizeof(m[0]);
	int i = 0;
	for(i = 0; i < size; i++)
	{
		m[i].print();
	}

	return 0;
}

        结果为:

constructor
constructor
3,4
constructor0
-858993460,-858993460
constructor
constructor
constructor
constructor
constructor0
7,8
9,10
11,12
0,0


       一个小问题: 上面程序中, 用户不写默认构造函数可以吗?  不可以, 这样编译会出错。 当且仅当类中没有构造函数的时候, 编译器会为它创建一个, 所以下面程序是对的:

 

#include <iostream>
using namespace std;

class A
{ 
};

int main()
{
	A a1;
	return 0;
}

 

 

 

 

 


本文转载:CSDN博客