构造函数
1、它主要用于为对象分配空间,进行初始化。
2、构造函数名必须与类名相同,可以有任意类型的参数,但不能有返回值。
3、它不需要用户调用,在建立对象时会自动执行。
#include <iostream>
using namespace std;
class compute
{
public:
compute(int a, int b);
int add();
private:
int c_a, c_b;
};
int compute::add()
{
return c_a + c_b;
}
//在初始化时,对私有数据赋值
compute::compute(int a, int b)
{
c_a = a, c_b = b;
}
采用构造函数给数据成员赋值
方法1:类名 对象名(构造函数参数值)
int main()
{
compute obj1(10, 20);
cout << obj1.add() << endl;
}
方法2:类名 *指针变量名 = new 类名(构造函数参数值)
int main()
{
compute* p = new compute(10, 20);
cout << p->add() << endl;
}
此外,构造函数的参数也可以设置默认值:
class compute
{
public:
compute(int a = 0, int b = 0);
int add();
private:
int c_a, c_b;
};
int compute::add()
{
return c_a + c_b;
}
//在初始化时,对私有数据赋值
compute::compute(int a, int b)
{
c_a = a, c_b = b;
}
析构函数
作用:它具有与构造函数相反的作用,用于撤销对象时的空间清理任务,即释放空间。
结构:~构造函数名()
性质:
1、没有参数、返回值,不能被重载(只能有一个)。
2、在撤销对象时,编译系统自动执行析构函数。
#include <iostream>
using namespace std;
class compute
{
public:
compute(int a, int b);
~compute();//析构函数
int add();
private:
int c_a, c_b;
};
int compute::add()
{
return c_a + c_b;
}
compute::compute(int a, int b)
{
c_a = a, c_b = b;
}
compute::~compute(){}
int main()
{
compute* p = new compute(10, 20);
cout << p->add() << endl;
}
析构函数自动调用情况:
- 如果定义了一个全局对象,则在程序流程离开其作用域时,调用该全局对象的析构函数。
- 如果一个对象定义在一个函数体内,则当这个函数被调用结束时,该对象应该被释放,析构函数被自动调用。
- 若一个对象是使用
new
运算符创建的,在使用delete
运算符释放它时,delete
会自动调用析构函数。
注:在没有定义析构函数的情况下, 编译器会自动生成一个默认析构函数。
构造函数重载
class compute
{
public:
compute(int a, int b);
compute(int x, int y, int z);
~compute();
int subst();
private:
int c_a, c_b;
};
拷贝构造函数
作用:在建立一个新对象时,用一个已存在的对象初始化这个新对象。
特点:
1、函数名与类名相同,没有返回值。
2、具有唯一参数,参数为对同类对象的引用。
3、每个类都必须有一个拷贝构造函数。可以自己定义拷贝构造函数,用于按照需要初始化新对象;如果没有定义类的拷贝构造函数,系统就会自动生成一个默认拷贝构造函数,用于复制出与数据成员值完全相同的新对象。
定义格式:
类名::类名(const 类名 &对象名)
{拷贝构造函数的函数体;}
具有拷贝构造函数的类示例:
class compute
{
public:
compute(int a, int b);
compute(const compute& p);//拷贝构造函数,不自定义也可以,编译器会自动生成
~compute();
int subst();
private:
int c_a, c_b;
};
compute::compute(int a, int b)
{
c_a = a, c_b = b;
}
compute::compute(const compute& p)
{
c_a = p.c_a, c_b = p.c_b;
}
int compute::subst()
{
return c_a - c_b;
}
compute::~compute(){}
调用拷贝构造函数:
int main()
{
compute out(10, 20);
compute out2 = out;//调用1
compute out3 = out2;//调用2
cout << out.subst() << endl;
}
深拷贝和浅拷贝
浅拷贝指,利用编译器默认生成的拷贝构造函数来初始化新建对象,当类中具有指针类型的数据时,容易出错。