一个类中包含:构造函数、析构函数与赋值函数。
每个类只有一个析构函数和一个赋值函数,但可以有多个构造函数(包含一个拷贝构造函数,其它的称为普通构造函数)。
类的定义的基本形式
class 类名
{
public:
公共成员函数
公共变量
private:
私有成员函数
私有成员数据
protected:
保护成员函数
保护成员数据
};
公共成员函数
默认构造函数,即便不写出来,编译器也会生成一个。
默认拷贝构造函数,不写编译器也会生成一个
析构函数
默认赋值函数
类的定义一般在.h文件中编写
类的结构
A() //默认构造函数
A(const A&); //默认拷贝构造函数
~A(); //析构函数
A& operator=(const A& a); //默认赋值函数
类与结构体的区别:
结构体默认访问方式是public,而类默认访问方式是private
构造函数的作用:
给对象一个标识
为数据成员开辟内存空间
完成数据成员的初始化工作 构造函数的特点:
构造函数与类同名
构造函数没有返回值类型修饰
构造函数可以有参数
构造函数支持重载
构造函数允许参数默认方式调用
构造函数初始化列表
构造函数(传入的参数):初始化列表 变量名(初始化值)
例如: Computer::Computer():count(1),name("耳机"),price(100)
{
}
Computer::Computer(const char *name, const float price) : count(1)
{
strcpy(this->name , name);
this->price = price;
}
//拷贝构造函数
Computer::Computer(const Computer & other):count(1)
{
strcpy(this->name, other.name);
this->price = other.price;
}
//赋值函数
Computer & Computer::operator=(const Computer & other)
{
strcpy(this->name, other.name);
this->price = other.price;
return *this;
}
析构函数及其特点
与类同名,之前冠以波浪号,以区别构造函数
析构函数没有返回类型,也不能指定参数 对象超出其作用域被撤销 或在对象作用域结束时,系统会自动调用析构函数
可以在类内部定义,也可以在类的外部定义
一般地,定义为公有成员
没有返回类型,也没有参数
析构函数可以被显式地调用
对象在使用new动态分配内存,在调用delete释放内存时,同样也会自动调用析构函数
析构函数的声明
~Computer();
实现
Computer::~Computer()
{
}
class 类名
{
public:
公共成员函数
公共变量
private:
私有成员函数
私有成员数据
protected:
保护成员函数
保护成员数据
};
公共成员函数
默认构造函数,即便不写出来,编译器也会生成一个。
默认拷贝构造函数,不写编译器也会生成一个
析构函数
默认赋值函数
类的定义一般在.h文件中编写
类的结构
A() //默认构造函数
A(const A&); //默认拷贝构造函数
~A(); //析构函数
A& operator=(const A& a); //默认赋值函数
类与结构体的区别:
结构体默认访问方式是public,而类默认访问方式是private
构造函数的作用:
给对象一个标识
为数据成员开辟内存空间
完成数据成员的初始化工作 构造函数的特点:
构造函数与类同名
构造函数没有返回值类型修饰
构造函数可以有参数
构造函数支持重载
构造函数允许参数默认方式调用
构造函数初始化列表
构造函数(传入的参数):初始化列表 变量名(初始化值)
例如: Computer::Computer():count(1),name("耳机"),price(100)
{
}
Computer::Computer(const char *name, const float price) : count(1)
{
strcpy(this->name , name);
this->price = price;
}
//拷贝构造函数
Computer::Computer(const Computer & other):count(1)
{
strcpy(this->name, other.name);
this->price = other.price;
}
//赋值函数
Computer & Computer::operator=(const Computer & other)
{
strcpy(this->name, other.name);
this->price = other.price;
return *this;
}
析构函数及其特点
与类同名,之前冠以波浪号,以区别构造函数
析构函数没有返回类型,也不能指定参数 对象超出其作用域被撤销 或在对象作用域结束时,系统会自动调用析构函数
可以在类内部定义,也可以在类的外部定义
一般地,定义为公有成员
没有返回类型,也没有参数
析构函数可以被显式地调用
对象在使用new动态分配内存,在调用delete释放内存时,同样也会自动调用析构函数
析构函数的声明
~Computer();
实现
Computer::~Computer()
{
}