本文主要是介绍C++笔记——构造函数与析构函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*构造函数:声明类的对象时,该类的构造函数会自动被调用*作用:构造函数是用于初始化类的成员变量**类的初始化列表:作用也是为了初始化类的成员,它是在类的构造函数调用之前就将类的相关成员变量初始化***析构函数:在类对象被销毁时,自动调用,调用顺序与构造函数相反*作用:做善后清理工作
*/
class Person
{
public:Person();Person(const string &name, const string &sex, int age);~Person();
private:string m_name;string m_sex;int m_age;
};Person::Person()
{cout << "Person()" << endl;m_name = "Person";m_sex = "man";m_age = 18;
}Person::Person(const string &name, const string &sex, int age):m_name(name),m_sex(sex),m_age(age)//类成员变量初始化的顺序以成员变量在类中声明的顺序为准,与在初始化列表中的顺序无关
{cout << "Person(...)" << endl;
}Person::~Person()
{cout << "~Person()" << endl;
}
类的引用、常量成员只能用类的初始化列表来初始化
class Person
{
public:Person(const string &name, const string &sex, int age, const int &var);~Person();void print();
private:string m_name;string m_sex;int m_age;int &m_age2;//引用成员int &m_age3;//引用成员const int m_number;//常量成员const int &m_age4;//const引用成员
};Person::Person(const string &name, const string &sex, int age, const int &var):m_name(name),m_sex(sex),m_age(age),m_age2(m_age),m_age3(age),m_number(1),m_age4(var)
{cout << "Person(...)" << endl;
}Person::~Person()
{cout << "~Person()" << endl;
}void Person::print()
{cout << "name:" << m_name<< " sex:" << m_sex<< " age:" << m_age<< " age2:" << m_age2<< " age3:" << m_age3<< " number:" << m_number<< " age4:" << m_age4 << endl;cout << "age address:" << &m_age << endl;cout << "age2 address:" << &m_age2 << endl;cout << "age3 address:" << &m_age3 << endl;cout << "age4 address:" << &m_age4 << endl;
}int main(int argc, char *argv[])
{int t_age = 20;Person p("AS","man",t_age,t_age);p.print();cout << "t_age address:" << &t_age << endl;return 0;
}
类的成员变量可以是该类的指针、引用、其它类的对象(类的组合)
class Game//游戏类
{
public:Game():m_name(""),m_level(0){cout << "Game()" << endl;}Game(const string &name, int level):m_name(name),m_level(level){cout << "Game(...)" << endl;}~Game(){cout << "~Game()" << endl;}private:string m_name;int m_level;
};class Person
{
public:Person();~Person();
private:Person *m_p;Person &m_person;Game m_game;
};Person::Person():m_p(0),m_person(*this),m_game("LOL",0)
{cout << "Person()" << endl;
}Person::~Person()
{cout << "~Person()" << endl;
}
这篇关于C++笔记——构造函数与析构函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!