1. 构造函数
为什么引入构造函数?
看一看之前写的程序:
如图所示,该部分的设置名字以及设置年龄分别用来两个函数,这回变的非常麻烦。所以提出构造函数的概念,
#include <iostream> using namespace std; class Person { private: char *name; int age; char *work; public: Person() {cout <<"Pserson()"<<endl;} Person(char *name) { cout <<"Pserson(char *)"<<endl; this->name = name; } Person(char *name, int age, char *work = "none") //char *work = "none",初始化的时候如果说,work没有参数,那么就赋值none { cout <<"Pserson(char*, int)"<<endl; this->name = name; this->age = age; this->work = work; } //构造函数,没有返回值,没有定义返回类型。 /* void setName(char *n) { name = n; } int setAge(int a) { if (a < 0 || a > 150) { age = 0; return -1; } age = a; return 0; } */ void printInfo(void) { //printf("name = %s, age = %d, work = %s\n", name, age, work); cout<<"name = "<<name<<", age = "<<age<<", work = "<<work<<endl; } }; int main(int argc, char **argv) { Person per("zhangsan", 16);//根据函数参数调用函数 Person per2; /* 调用无参数构造函数 */ Person per3(); /* int fun(); */ per.printInfo(); return 0; }
我们还有没有其他办法来实例化一个对象呢?
有的,这里我们直接定义
#include <iostream> using namespace std; class Person { private: char *name; int age; char *work; public: Person() {cout <<"Pserson()"<<endl;} Person(char *name) { cout <<"Pserson(char *)"<<endl; this->name = name; } Person(char *name, int age, char *work = "none") { cout <<"Pserson(char*, int)"<<endl; this->name = name; this->age = age; this->work = work; } /* void setName(char *n) { name = n; } int setAge(int a) { if (a < 0 || a > 150) { age = 0; return -1; } age = a; return 0; } */ void printInfo(void) { //printf("name = %s, age = %d, work = %s\n", name, age, work); cout<<"name = "<<name<<", age = "<<age<<", work = "<<work<<endl; } }; int main(int argc, char **argv) { Person per("zhangsan", 16); Person per2; /* 调用无参数构造函数 */ Person per3(); /* int fun(); */ Person *per4 = new Person;//临时动态创建一个person Person *per5 = new Person(); //我们使用关键字new在堆上动态创建一个对象时,它实际上做了三件事:获得一块内存空间、调用构造函数、返回正确的指针。 Person *per6 = new Person[2]; Person *per7 = new Person("lisi", 18, "student"); Person *per8 = new Person("wangwu", 18); per.printInfo(); per7->printInfo(); per8->printInfo(); delete per4; delete per5; delete []per6; delete per7; delete per8; //删掉new创建出来的内存 return 0; }