2021-03-10

1.构造函数(一般用于初始化赋值)
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。

构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。
可用于为某些成员变量设置初始值。

#include

using namespace std;

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // 这是无参构造函数

private:
double length;
};

// 成员函数定义,包括构造函数
Line::Line(void)
{
cout << “Object is being created” << endl;
}

void Line::setLength( double len )
{
length = len;
}

double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
Line line;

// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值

#include

using namespace std;

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // 这是有参构造函数

private:
double length;
};

// 成员函数定义,包括构造函数
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}

void Line::setLength( double len )
{
length = len;
}

double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
Line line(10.0);

// 获取默认设置的长度
cout << "Length of line : " << line.getLength() <<endl;
// 再次设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

2.复制构造函数

复制构造函数通常用于:

通过使用另一个同类型的对象来初始化新创建的对象。

复制对象把它作为参数传递给函数。

复制对象,并从函数返回这个对象

#include
using namespace std;

调用复制构造函数的三种情况
class Point{
public:
Point(int xx=0,int yy=0){
x=xx;
y=yy;
}
Point(Point &p);
int getX(){
return x;
}
int getY(){
return y;
}
private:
int x,y;
};

Point::Point(Point &p){
x=p.x;
y=p.y;
cout<<“调用了复制构造函数!”<<endl;
}

void fun1(Point p){
cout<<p.getX()<<endl;
}

Point fun2(){
Point a(1,2);
return a;
}

int main(){
Point a(4,5);
Point b=a; //情况一,用一种对象初始化另一种对象。第一次调用复制构造函数。
cout<<b.getX()<<endl;
fun1(b); //情况二,对象b作为函数的实参。第二次调用复制构造函数。
b=fun2(); //情况三,函数的返回值是类对象,函数返回时,调用复制构造函数
cout<<b.getX()<<endl;
return 0;
}

3.析构函数和构造函数类似
析构函数主要作用就是释放资源,避免内存泄漏。

1、析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。析构函数往往用来做“清理善后” 的工作(例如在建立对象时用new开辟了一片内存空间。

2、析构函数如果我们不写的话,C++ 会帮我们自动的合成一个,就是说:C++ 会自动的帮我们写一个析构函数。很多时候,自动生成的析构函数可以很好的工作,但是一些重要的事迹,就必须我们自己去写析构函数。

3、按照 C++ 的要求,只要有 new 就要有相应的 delete 。这个 new 是在构造函数里 new 的,就是出生的时候。所以在死掉的时候,就是调用析构函数时,我们必须对指针进行 delete 操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值