1-构造函数.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
class Array
{
private:
int *data; //数组的起始地址
int size; //数组的容量
public:
Array(); //无参构造函数 函数名和类名一样 没有返回值 完成对象的初始化操作
Array(int s); //有参构造函数
Array(const Array &a); //拷贝构造函数
void setVal(int Index, int val);
int getVal(int Index);
~Array(); //析构函数 函数名是类名加~ 没有参数 没有返回值
};
Array::Array()
{
cout << "Array的无参构造函数" << endl;
size = 5;
data = (int *)malloc(sizeof(int) * size);
}
Array::Array(int s)
{
cout << "Array的有参构造函数" << endl;
size = s;
data = (int *)malloc(sizeof(int) * size);
}
Array::Array(const Array &a)
{
cout << "Array的拷贝构造函数" << endl;
}
void Array::setVal(int Index, int val)
{
data[Index] = val;
}
int Array::getVal(int Index)
{
return data[Index];
}
Array::~Array()
{
cout << "Array析构函数" << endl;
if (data != NULL)
{
free(data);
}
}
void f(Array a)
{
}
int main()
{
Array a1; //创建对象的时候,自动调用构造函数
Array a2(10);
Array a3 = Array(10);
Array a4 = (10);
for (int i = 0; i < 5; i++)
{
a1.setVal(i, i + 1);
}
for (int i = 0; i < 5; i++)
{
cout << a1.getVal(i) << " ";
}
cout << endl;
cout << "********" << endl;
f(a1); //函数传参,会调用拷贝构造函数
//Array a5(a2); //调用拷贝构造函数 用a2构造a5
return 0; //释放对象的时候,自动调用析构函数
}
2-深拷贝.cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
class Array
{
private:
int *data;
int size;
public:
Array(int s)
{
cout << "有参构造函数" << endl;
size = s;
data = (int *)malloc(sizeof(int) * size);
}
Array(const Array &a) //深拷贝
{
cout << "Array拷贝构造函数" << endl;
size = a.size;
data = (int *)malloc(sizeof(int) * size);
for (int i = 0; i < size; i++)
{
data[i] = a.data[i];
}
}
~Array()
{
cout << "析构函数" << endl;
if (data != NULL)
{
free(data);
}
}
};
int main()
{
Array a1(10);
Array a2(a1); //编译器为每个类提供默认的拷贝构造函数 只做简单的赋值(浅拷贝)
return 0;
}
3-默认构造函数.cpp
#include <iostream>
using namespace std;
class Test1
{
public:
};
class Test2
{
public:
Test2()
{
cout << "Test2无参构造函数" << endl;
}
};
class Test3
{
public:
Test3(int a)
{
}
};
class Test4
{
public:
Test4(const Test &t)
{
}
};
int main()
{
Test1 t1; //编译器会默认提供无参构造函数
Test1 tt(t1); //编译器提供默认的拷贝构造函数(浅拷贝)
Test2 t2; //一旦提供了无参构造函数,编译器不再提供默认无参构造函数
//Test3 t3; //一旦提供了有参构造函数,编译器不再提供默认无参构造函数
Test4 t4; //一旦提供了拷贝构造函数,编译器不再提供无参构造函数
return 0;
}
4-匿名对象.cpp
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test无参构造函数" << endl;
}
~Test()
{
cout << "Test析构函数" << endl;
}
};
int main()
{
Test(); //匿名对象,本行代码执行完,立即被释放
Test();
return 0;
}