类与对象的封装
一个类的基本构造
// class 关键字定义类
class Student
{
// 属性
// 方法
};
访问修饰符
访问修饰符 | 作用域 |
---|---|
public | 类内可以访问,类外也可以访问,公共权限,可以inherit ,类外可以读写 |
protected | 受保护权限,类内可以访问,类外不可以访问,可以inherit ,类外不可读写 |
private | 私有权限,类内可以访问,类外不可以访问,不可以inherit ,类外不可读写 |
构造函数与析构函数
编译器在通常情况下,一般会给一个类默认提供三个函数
- 无参构造函数
- 析构函数
- 拷贝构造函数
构造函数
- 无返回值,不用写
void
关键字 - 可以有参数,可以重载
- 函数名称与类名相同
- 程序在调用对象时会自动调用函数,无需手动调用,而且一个对象有且只有一次会调用构造函数
class Student
{
public :
Student()
{
}
// 构造函数可以重载
Student(int id,string name)
{
}
};
构造函数的调用
#include <iostream>
#include <string>
using namespace std;
class Student
{
private :
int id;
string name;
public :
// 默认构造函数
Student()
{
cout << "默认(无参构造函数)" << endl;
}
// 有参构造函数
Student(int id, string name)
{
this->id = id;
this->name = name;
cout << "有参构造函数, id:" << this->id << "name:" << this->name << endl;
}
// 拷贝构造函数
Student(const Student& student)
{
this->id = student.id;
this->name = student.name;
cout << "(引用类型为参数叫拷贝构造参数)有参构造函数, id:" << this->id << "name:" << this->name << endl;
}
};
int main()
{
// 括号调用
Student s1; // 调用无参构造函数时不能加括号,如果加了编译器认为这是一个函数声明
Student s2(1, "Davi");
Student s3(s2);
// 显示法
Student ss1 = Student();
Student ss2 = Student(1,"Davi");
Student ss3 = Student(ss2);
//隐式转换法
Student sss2 = ss2;
// 不能利用拷贝构造函数初始化匿名函数
system("pause");
return 0;
}
析构函数
- 析构函数,没有返回值也不写
void
- 函数名称与类名相同,在名称前面加上符号
~
- 函数不能有参数,所以也不能有重载
- 程序在对象销毁前会自动调用析构函数,无须手动调用,一个对象有且只有一次会调用析构函数
class Student
{
public :
~ Student()
{
}
};
构造函数里面的拷贝函数类型
拷贝函数在什么时候会被调用
- 使用一个创建完毕的对象来初始化一个新对象时
- 值传递的方式给函数参数传参
- 以值的方式返回局部对象
#include <iostream>
using namespace std;
// 定义一个类
class Student
{
int id;
string name;
public :
// 默认构造函数
Student()
{
this->id = 0;
this->name = "";
cout << "默认构造无参函数" << endl;
}
// 有参构造函数
Student(int id, string name)
{
this->id = id;
this->name = name;
cout << "有参构造函数" << endl;
}
// 拷贝构造函数
Student(const Student& student)
{
cout << "拷贝构造函数" << endl;
this->id = student.id;
this->name = student.name;
}
};
/// <summary>
/// 当一个对象被当作一个参数放进函数中时
/// 其实就相当于这个对象被复制拷贝一份
/// </summary>
void test01(Student s)
{
cout << (int)&s << endl;
}
/// <summary>
/// 在函数内部返回一个对象,其实也是拷贝了一份对象return出去
/// </summary>
/// <returns></returns>
Student test02()
{
Student s;
cout << "函数内部对象的地址:" << (int)&s << endl;
return s;
}
int main()
{
Student s;
test01(s);
cout << "---------------------------" << endl;
cout << "test02返回的函数地址" << (int)&test02() << endl;
return 0;
}