版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42528266/article/details/102750979
memset函数是将较大的数据结构(比如对象、数组等)内存清零的比较快的方法
#include <iostream>
using namespace std;
struct Person {
int m_age;
Person() {
cout << "Person()" << endl;
// this->m_age = 0;
memset(this, 0, sizeof(Person));
}
Person(int age) {
cout << "Person(int age)" << endl;
this->m_age = age;
}
};
// 全局区
Person g_person1; // Person()
Person g_person2(); // 这是一个函数声明,函数名叫g_person2,无参,返回值类型是Person
Person g_person3(10); // Person(int age)
int main() {
// 栈空间
Person person1; // Person()
Person person2(); // 函数声明,函数名叫person2,无参,返回值类型是Person
Person person3(20); // Person(int age)
// 堆空间
Person *p1 = new Person; // Person()
Person *p2 = new Person(); // Person()
Person *p3 = new Person(30); // Person(int age)
// 4次无参构造函数
// 3次有参构造函数
getchar();
return 0;
}
#include <iostream>
using namespace std;
struct Person {
int m_age;
/*Person() {
cout << "Person()" << endl;
this->m_age = 0;
}*/
};
void test() {
//int *p = new int();
//memset(p, 1, 4);
//// 0000 0001 0000 0001 0000 0001 0000 0001
//cout << *p << endl;
//int *p = (int *) malloc(8);
//free(p);
/*int *p = (int *) malloc(2);
*p = 5;*/
// 0000 0000 0000 0000 0000 0000 0000 0101
}
// 全局区(成员变量初始化为0)
Person g_person;
int main() {
// 栈空间(成员变量没有初始化)
Person person;
// 堆空间
Person *p1 = new Person; // 成员变量没有初始化
Person *p2 = new Person(); // 成员变量有初始化
cout << "g_person " << g_person.m_age << endl;
cout << "p1 " << p1->m_age << endl;
cout << "p2 " << p2->m_age << endl;
getchar();
return 0;
}
#include <iostream>
using namespace std;
class Person {
int m_age;
public:
// 对象创建完毕的时候调用
Person() {
cout << "Person()" << endl;
this->m_age = 0;
}
Person(int age) {
cout << "Person(int age)" << endl;
this->m_age = age;
}
// 对象销毁(内存被回收)的时候调用
~Person() {
cout << "~Person()" << endl;
}
};
//void test() {
// Person person;
//}
int main() {
Person person;
/*{
Person person;
}*/
/*Person *p = new Person();
delete p;*/
/*Person *p = (Person *) malloc(sizeof(Person));
free(p);*/
getchar();
return 0;
}
#include <iostream>
using namespace std;
struct Car {
int m_price;
Car() {
cout << "Car()" << endl;
}
~Car() {
cout << "~Car()" << endl;
}
};
struct Person {
int m_age; // 4
Car *m_car; // 4
// 初始化工作
Person() {
cout << "Person()" << endl;
this->m_car = new Car();
/*Car car;
this->m_car = &car;*/
}
// 内存回收、清理工作(回收Person对象内部申请的堆空间)
~Person() {
cout << "~Person()" << endl;
delete this->m_car;
}
};
void test() {
Person *p = new Person();
delete p;
}
int main() {
test();
getchar();
return 0;
}