一、构造函数一大功能就是初始化成员变量
(1)默认的构造函数不带参数,也无初始化功能。
(2)如没有其他构造函数,默认构造函数可以省略,如果有其它构造函数,则需要写构造函数。
(3)如果在栈上分配对象的内存,不需要初始化则构造函数不加(),如果初始化需要带参。
二、成员初始化列表
(1)一般用于带参构造函数中,用来给属性传参赋值。
(2)成员初始化列表与构造函数之间用冒号隔开,列表与列表之间用逗号隔开
(3)初始化列表可以代替构造函数中的赋值语句
三、构造函数使用参数默认值
(1)class声明时可以给函数形参一个默认值,如果在函数调用时不传参就使用默认值
(2)实际调用时不写默认形参,但是执行时按照默认参数执行
(3)有默认值情况,要注意实际调用不能有重载歧义,否则编译不能通过。
(4)所有参数都带默认值的构造函数,一个可以顶多个构造函数。
四、编程实战
/*person.hpp*/
#ifndef __PERSON_H__
#define __PERSON_H__
#include<string>
using namespace std;
class person
{
//访问权限
public:
//属性
string name; //名字
int age; //年龄
bool male; //性别
int *pInt; //int类型的野指针
//构造函数和析构函数
// person(); //默认构造函数
// person(string myname); //自定义构造函数1
person(string myname = "heyunji", int myage = 25, bool mymale = 1); //自定义构造函数2
~person(); //默认析构函数
//方法
void work(void);
void eat(void);
void sleep(void);
void printf(void);
private:
};
#endif
/*person.cpp*/
#include "person.hpp"
#include <iostream>
using namespace std;
//引用class中函数的方法
void person::work(void)
{
// cout << this->name << " work" << endl;
if (this->male)
{
cout << this->name << " coding" << endl;
}
else
{
cout << this->name << " shopping" << endl;
}
}
void person::eat(void)
{
cout << this->name << " eat" << endl;
}
void person::printf(void)
{
cout << " name =" << name << endl;
cout << " age =" << age << endl;
cout << " male =" << male << endl;
}
void person::sleep(void)
{
// cout << "value of this->pIn =" << *pInt << endl;
for (int i = 0; i < 100; i++)
{
this->pInt[i] = i;
}
for (int i = 0; i < 100; i++)
{
cout << "value of this->pIn i=" << pInt[i] << endl;
}
cout << this->name << " sleep" << endl;
}
person::person(string myname, int myage, bool mymale):name(myname),age(myage),male(mymale) //自定义构造函数2
{
this->pInt = new int[100];
cout << "userdefined constructor" << endl;
}
/*
person::person()
{
//默认构造函数是空的
cout << "default constructor" << endl;
}
person::person(string myname) :name(myname)
{
//默认构造函数是空的
// this->name = name; //构造函数后同时对对象中的name属性进行初始化
//在构造函数中对calss中需要分配动态内存的指针进行分配
// this->pInt = new int(55);
this->pInt = new int[100];
cout << "userdefined constructor" << endl;
}
*/
person::~person()
{
// delete this->pInt; //单个变量析构
delete[] this->pInt; //数组变量析构
//默认析构函数
cout << "userdefine destructor" << endl;
}
/*main.cpp*/
#include <iostream>
#include "person.hpp"
using namespace std;
int main(void)
{
//人的一天生活
string s1 = "linux";
person pPerson(s1); //创建一个person对象
// pPerson->name = "zhangsan";
// pPerson.age = 0;
// pPerson.male = 0;
pPerson.printf();
pPerson.eat();
pPerson.work();
pPerson.eat();
pPerson.work();
// pPerson.sleep();
//使用完对象后就销毁
// delete pPerson;
getchar();
return 0;
}
版权声明:本文为weixin_44764479原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。