C++之构造函数,析构函数,拷贝构造函数

一、定义

    构造函数:是在一个定义在类里面的函数,它的作用是在你创建这个类的对象时被自动调用。

                    如果你自己定义了则调用自己定义的,否则调用默认的。

    析构函数:是一个在类里面定义的函数,它的作用是在你的类对象死亡时被调用删除这个类对

                    象同样的你自己定义了则调用自己的,否则调用默认的。

    在了解拷贝构造函数之前先要了解深拷贝和浅拷贝:

         如果一个类拥有资源,当这个类的对象发生复制时会给新的对象进行资源分配,那么我们称

         之为深拷贝,否则称为浅拷贝。

    拷贝构造函数:在你未定义拷贝构造函数时,当你的类对象进行复制时默认调用的是c++提供的

                            拷贝构造函数,即为浅拷贝;若你在定义拷贝构造函数里分配了新对象所需要的

                            资源则为深拷贝。

二、使用

    在这里我用一个类来对构造函数,析构函数以及拷贝构造函数进行说明。

    拷贝构造函数是在类对象复制的时候会被调用。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


using namespace std;


class A
{
	public :
		A(const char *p)
		{
			str=new char[10];
			strcpy(str,p);
			printf("这是A的构造函数\n");
		}
		A(const A &c)
		{
			str = new char[10];
			if(str!=0)
			strcpy(c.str,str);
			printf("这是A的拷贝构造函数\n");	
		}		
		~A()
		{
			delete  str;
			printf("这是A的析构函数\n"); 
		}
	public :
		    char *str;	
};


class b:public A
{
	public :
		b(const char *s,const char *p):A(p)//注意子类构造函数的写法当父类和子类的构造函数都含有参数时
		{
			string = new char[10]; 
			strcpy(string,s);
			str=new char[10];
			strcpy(str,p);
			printf("这是b的构造函数\n");
		}
		b(const b &c):A(c)//!注意子类拷贝构造函数的写法
		{	
			this->string = new char[10];
			strcpy(c.string,string);
			this->str = new char[10];
			strcpy(c.str,str);
			printf("这是b的拷贝构造函数\n"); 
		}
		~b()
		{
			delete string;
			printf("这是b的析构函数\n"); 
		}
	public :
		char *string;	
};
int main()
{
	A a("lucifer");
	printf("----------------------\n");
	b c("lucifer","devil");
	printf("----------------------\n");
	A d = a;
	printf("----------------------\n");		
}	


    在这里我们看到了先调用了父类的构造函数,然后又调用了子类的构造函数。在析构时又先调用了子类的

    析构函数然后调用了父类的析构函数。

    然后要注意了当父类和子类的构造函数和拷贝构造函数都含有参数时,你必须注意到构造函数的初始化列表,

    还有拷贝构造函数。

    !欢迎各位来指出不足之处


        

猜你喜欢

转载自blog.csdn.net/qq_41003024/article/details/80212335