文章目录
类与对象的封装一个类的基本构造访问修饰符构造函数与析构函数构造函数构造函数的调用
析构函数
构造函数里面的拷贝函数类型拷贝函数在什么时候会被调用
类与对象的封装
一个类的基本构造
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
;
}
};
void test01(Student s
)
{
cout
<< (int)&s
<< endl
;
}
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;
}