析构和构造
#include <iostream> #include <cstring> using namespace std; class Person { public: Person() { cout << "构造函数调用" << endl; pName = (char *)malloc(sizeof("John")); strcpy(pName, "John"); mTall = 150; mMoney = 100; } ~Person() { cout << "析构函数调用!" << endl; if (pName!=NULL) { free(pName); pName = NULL; } } public: char *pName; int mTall; int mMoney; }; int main() { Person person; cout << person.pName << endl; cout << person.mTall << endl; cout << person.mMoney << endl; return 0; }
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 class Person 5 { 6 public: 7 Person() 8 { 9 cout << "无参构造" << endl; 10 } 11 Person(int age) 12 { 13 cout << "有参构造" << endl; 14 mAge = age; 15 } 16 //拷贝构造 17 Person(const Person &person) 18 { 19 cout << "拷贝构造" << endl; 20 mAge = person.mAge; 21 } 22 void PrintPerson() 23 { 24 cout << "Age:" << mAge << endl; 25 } 26 private: 27 int mAge; 28 }; 29 //无参调用 30 void test01() 31 { 32 Person person1; 33 person1.PrintPerson(); 34 } 35 //有参调用 36 void test02() 37 { 38 //第一种括号法 39 Person person01(100); 40 person01.PrintPerson(); 41 //调用拷贝构造函数 42 Person person02(person01); 43 person02.PrintPerson(); 44 //第二种匿名对象//显式调用 45 Person(200).PrintPerson(); 46 47 Person person03 = Person(300); 48 person03.PrintPerson(); 49 //第三种=号法,隐式转换 50 Person person04 = 100;//Person person04=Person(100); 51 person04.PrintPerson(); 52 } 53 int main() 54 { 55 test02(); 56 return 0; 57 }
道阻且长,行则将至