
一,构造函数和析构函数
对象的初始化和清理是两个重要的安全问题
为了解决上述两个问题,c++提供了构造函数和析构函数
1. 异同
(1)相同点:
A.如果我们不提供构造和析构,编译器会自动为我们提供这两个函数,
注意:由编译器提供的构造函数和析构函数是空实现。
B.都没有返回值且不写void
C.无需手动调用,且只会调用一次
(2)不同点:
构造函数可以传入参数。析构函数不能传入参数。意味着构造函数可以发生函数重载,而析构函数不能
2. 构造语法:
简单代码如下:
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
Person(){
cout << "默认构造函数的调用" << endl;
}
~Person() {
cout << "析构函数的调用" << endl;
}
};
int main() {
Person a;
system("pause");
return 0;
}
二.构造函数的分类及调用
1.两种分类方式:
A.按照参数:有参构造(默认构造),无参构造
B.按照类型:普通构造,拷贝构造
2.三种调用方式:
括号法
显示法
隐式转换法
注意事项见如下代码块
#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
Person(){
cout << "默认构造函数的调用" << endl;
}
Person(int a) {
cout << "含参构造函数的调用" << endl;
}
Person(const Person& p)
{
cout << "拷贝构造函数的调用" << endl;
age = p.age;
}
~Person() {
cout << "析构函数的调用" << endl;
}
int age;
};
int main() {
//1.括号法
Person a;
a.age = 500;
cout << "a的年龄为: " << a.age << endl;
Person b(10);
Person c(a);
//2.显示法
Person d = Person(10);
Person e=Person(c);
cout << "e的年龄为: " << e.age << endl;
Person(20);//匿名对象特点:前行代码结束后,系统会自动回收掉匿名对象。
cout << "aaa" << endl;
//注意:不能用拷贝函数初始化匿名对象,会认为person(p3)==person p3;
//3.隐式转换法
Person f =10;//与person f(10)等价
Person g = e;
cout << "g的年龄为: " << g.age << endl;
system("pause");
return 0;
}
运行结果如下:

注意:匿名对象的析构函数调用时机
1252

被折叠的 条评论
为什么被折叠?



