命名空间
.h头文件
备注:.h头文件中include
使用尖括号< >和双引号" “的区别在于头文件的搜索路径不同:
尖括号< >,编译器会到 系统路径下 查找头文件(.h);
双引号” ",编译器 先在 当前目录下 查找头文件,如果没找到,则再到 系统路径下 去查找。
(也就是说,使用双引号会比使用尖括号多一个查找路径)
#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
构造函数与析构函数
在C++中,有一种特殊的成员函数,它的名字和类名相同,没有返回值,不需要用户调用,该函数会在在创建对象时自动执行。这种特殊的成员函数就是构造函数(Constructor)。具体见.h头文件。定义与具体实现,有参还是无参。
程序
swl-constructor.cpp代码如下(示例):
#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;
}
main.c代码如下(示例):
#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;
}
结果
代码如下(示例):
Software_engineering 无参构造函数执行
Electronic_information 有参构造函数执行 姓名: 小霖 年龄: 23
Ending !!!
请按任意键继续. . .
Electronic_information 析构函数执行
Software_engineering 析构函数执行
总结
注意传参时,参数的数据类型,如: (“小林”, 23, 90.5f); //报错:无法将参数 1 从“ const char [5] ”转换为“ char * “
构造函数(Constructor)的名字和类名相同,在创建对象的同时执行,构造函数常用于初始化工作。
析构函数(Destructor)的名字前面有一个~符号。常用于释放分配的内存、关闭打开的文件等。
注意:析构函数没有参数,不能被重载,因此一个类只能有一个析构函数。
可以在构造函数的函数体中对成员变量一一赋值,也可以采用初始化列表。
//构造函数的初始化列表
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;
}