1.复习
- 构造函数用来给变量赋初值
2.拷贝构造:
(拷贝构造是特殊的构造函数)
定义: 用同类的对象给新的对象赋初值的过程
说明:
-
在定义一个类之后,编译器会自动补全三个(构造、拷贝、析构)函数
-
在没有自己定义的情况下,编译器会直接拷贝——浅拷贝
-
但是在涉及到指针操作的情况下就要自己定义拷贝——深拷贝(代码见student.cpp中student::student(const
student& other):i(0)部分)
3.类的常量成员:
3.1const修饰的常量成员
- 在初始化时必须在初始化形参列表中赋值
3.2类的常属性成员函数
-
格式:成员函数名()const;
-
作用:防止在成员函数里修改成员变量
说明:
-
const修饰的成员函数本质上修饰的是this指针
-
const修饰的成员函数不能调用非const成员函数
4.类的静态成员:
4.1static修饰的成员变量
-
格式: static 变量类型 变量名;
-
作用: static修饰后,变量公有,属于类中的全局变量
- (假设定义student类,那么name1,name2,,,都是具有student类性质的对象,当student类中定义了一个static成员变量A以后,那么name1,name2,,,中A的值均相同)
-
说明: 静态成员变量必须在类外初始化
-
初始化格式: 类型名 类名::静态变量名=值;
4.2 static修饰的成员函数
-
格式: static 函数类型 函数名(){语句;}
-
说明:
-
静态成员没有this指针,不能访问其它非静态成员函数或非静态成员变量
-
静态成员函数只能访问或者修改静态成员
-
-
说明:
-
类中包括成员变量和成员函数两大类
-
“对象”就是所定义的类的变量名
-
拷贝构造定义的参数必须是引用
-
原因:如果不定义引用,那么就是一个同类对象给新的对像赋值的过程,等价于调用拷贝构造,这将形成一个死循环
-
5. 代码实例
头文件
#pragma once
class student
{
private:
int ID;
char* name;
const int i;
public:
student();
student(int id, char name[]);
student(const student& other);//添加const可以防止在拷贝过程中参数被修改
void showData();
~student();
};
.cpp文件
#include "student.h"
#include<iostream>
#include<string>
student::student():i(0)
{
ID = 0;
name = new char[1];
strcpy(name, "");
}
student::student(int id, char name[]) : i(0)
{
ID = id;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
student::student(const student& other):i(0)
{
this->name = new char[strlen(other.name) + 1];
strcpy(this->name, other.name);//深拷贝方式
this->ID = other.ID;
}
void student::showData()
{
std::cout << ID << '\t' << name << std::endl;
}
student::~student()
{
if (name != nullptr)
{
delete[] name;
name = nullptr;
}
}
主函数文件
#include<iostream>
#include"student.h"
using namespace std;
void fun(student stu)
{
stu.showData();
}
int main()
{
student stu;
student stu2(12,"liu");
cout << "不带参函数拷贝构造展示" << endl;
fun(stu);
cout << endl<< "不带参函数拷贝构造展示" << endl;
fun(stu2);
cin.get();
return 0;
}