Espacios de nombres, constructores y destructores personalizados de C++

Espacios de nombres, constructores y destructores personalizados de C++


Espacios de nombres

Archivo de encabezado .h
Observaciones: La diferencia entre usar corchetes angulares < > y comillas dobles " " en el archivo de encabezado .h
es que la ruta de búsqueda del archivo de encabezado es diferente: los
corchetes angulares < >, el compilador buscará el encabezado archivo (.h);
comillas dobles " ", el compilador primero busca el archivo de encabezado en el directorio actual y, si no lo encuentra, va a la ruta del sistema para buscar.
(Es decir, usar comillas dobles agregará una ruta de búsqueda más que usar paréntesis angulares)

#ifndef SWL_CONSTRUCTOR_
#define SWL_CONSTRUCTOR_

#include <iostream>
#include <string>

using namespace std;

/*********************************************
 * 命名空间:College_Student	大学生
 * 类:Electronic_information	电子信息
		公有的:姓名
		私有的:年龄、分数
 * 类:Software_engineering		软件工程
		公有的:姓名
		私有的:年龄、分数
*********************************************/

namespace College_Student {
    
    
	class Electronic_information {
    
    
		public:
			char *m_name;
			Electronic_information();
			Electronic_information(char *name, int age, float score);
			~Electronic_information();

		private:
			int m_age;
			float m_score;
	};

	class Software_engineering {
    
    
	public:
		char *m_name;
		Software_engineering();
		~Software_engineering();

	private:
		int m_age;
		float m_score;
	};
}

#endif 


Constructores y Destructores

En C++, hay una función miembro especial cuyo nombre es el mismo que el nombre de la clase, no tiene valor de retorno y no necesita ser llamado por el usuario.Esta función se ejecutará automáticamente cuando se cree el objeto. Esta función miembro especial es el constructor (Constructor). Consulte el archivo de encabezado .h para obtener más detalles. Definición e implementación específica, con o sin parámetros.


programa

El código swl-constructor.cpp es el siguiente (ejemplo):

#include "swl-constructor.h"

using namespace College_Student;

Electronic_information::Electronic_information()
{
    
    
	cout << "Electronic_information 无参构造函数执行" << endl;
}

Electronic_information::Electronic_information(char *name, int age, float score)
{
    
    
	m_name = name;
	m_age = age;
	m_score = score;

	cout << "Electronic_information 有参构造函数执行 姓名: " << name << " 年龄: " << age << endl;
}

Electronic_information::~Electronic_information()
{
    
    
	cout << "Electronic_information 析构函数执行" << endl;
}


Software_engineering::Software_engineering()
{
    
    
	cout << "Software_engineering 无参构造函数执行" << endl;
}

Software_engineering::~Software_engineering()
{
    
    
	cout << "Software_engineering 析构函数执行" << endl;
}

El código main.c es el siguiente (ejemplo):

#include "swl-constructor.h"

using namespace std;


int main(int argc, char** argv)
{
    
    
	char my_name[] = "小霖";

	//无参构造
//	College_Student::Electronic_information william;
	College_Student::Software_engineering swl;
	//有参构造
//	College_Student::Electronic_information william("小林", 23, 90.5f); //报错:无法将参数 1 从“const char [5]”转换为“char *”
	//解决方法:方法一:强制类型转换(char*)  方法二:声明变量char name[]再赋值,传参
//	College_Student::Electronic_information william((char*)"小林", 23, 90.5f); //正常运行
	College_Student::Electronic_information william(my_name, 23, 90.5f); //正常运行

	cout << "Ending !!!" << endl;
	system("pause");

	return 0;
}

resultado

El código es el siguiente (ejemplo):

Software_engineering 无参构造函数执行
Electronic_information 有参构造函数执行 姓名: 小霖 年龄: 23
Ending !!!
请按任意键继续. . .
Electronic_information 析构函数执行
Software_engineering 析构函数执行


Resumir

Preste atención al tipo de datos del parámetro al pasar el parámetro, como: ("Xiaolin", 23, 90.5f); // Error: No se puede convertir el parámetro 1 de "const char [5]" a "char *"

El nombre del constructor (Constructor) es el mismo que el nombre de la clase, y se ejecuta al crear el objeto. El constructor se usa a menudo para la inicialización.

Los nombres de los destructores están precedidos por un símbolo ~. Comúnmente utilizado para liberar la memoria asignada, cerrar archivos abiertos, etc.
Nota: el destructor no tiene parámetros y no se puede sobrecargar, por lo que una clase solo puede tener un destructor.

Puede asignar valores a las variables miembro uno por uno en el cuerpo de la función del constructor, o puede usar una lista de inicialización.

//构造函数的初始化列表
Electronic_information::Electronic_information(char *name, int age, float score)
	: m_name(name)
	, m_age(age)
	, m_score(score)
{
    
    
	cout << "Electronic_information 有参构造函数执行 姓名: " << name << " 年龄: " << age << endl;
}

Supongo que te gusta

Origin blog.csdn.net/William_swl/article/details/127550823
Recomendado
Clasificación