类对象作为类成员

1.类的类成员的类中要有默认构造参数

2.构造顺序

当类对象作为类的成员时,构造顺序是先依次构造类成员的构造,然后再构造自己

3.析构顺序

析构与构造相反,先析构自己,再以相反顺序依次析构成员

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;

class Game
{
public:
    Game()
    {
        cout << "Game无参构造函数" << endl;
    }
    Game(string name)
    {
        m_name = name;
        cout << "Game有参构造函数" << endl;
    }

    ~Game()
    {
        cout << "Game析构函数" << endl;
    }

    string m_name;
};

class Phone
{
public:
    Phone()
    {
        cout << "Phone无参构造函数" << endl;
    }
    Phone(string name)
    {
        m_name = name;
        cout << "Phone有参构造函数" << endl;
    }

    ~Phone()
    {
        cout << "Phone析构函数" << endl;
    }

    string m_name;
};



class Person
{
public:
    Person()
    {
        cout << "Person无参构造函数" << endl;
    }
    Person(string name)
    {
        m_name = name;
        cout << "Person有参构造函数" << endl;
    }

    ~Person()
    {
        cout << "Person析构函数" << endl;
    }

    string m_name;
    Phone m_Phone;  //Phone和Game谁在前面先构造谁,跟类位置无关
    Game m_Game;
};



void Test201()
{
    Person p1;
}

int main()
{
    Test201();
    system("Pause");
    return 0;
}

结果:

 案例:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;

class Game
{
public:
    Game()
    {
        cout << "Game无参构造函数" << endl;
    }
    Game(string name)
    {
        m_name = name;
        cout << "Game有参构造函数" << endl;
    }

    ~Game()
    {
        cout << "Game析构函数" << endl;
    }

    string m_name;
};

class Phone
{
public:
    Phone()
    {
        cout << "Phone无参构造函数" << endl;
    }
    Phone(string name)
    {
        m_name = name;
        cout << "Phone有参构造函数" << endl;
    }

    ~Phone()
    {
        cout << "Phone析构函数" << endl;
    }

    string m_name;
};



class Person
{
public:
    Person()
    {
        cout << "Person无参构造函数" << endl;
    }
    Person(string name, string phoneName, string gameName):m_name(name),m_Phone(phoneName),m_Game(gameName) //需要类Phone和类Game有有参构造函数,不然报错
    {
        m_name = name;
        cout << "Person有参构造函数" << endl;
    }

    ~Person()
    {
        cout << "Person析构函数" << endl;
    }

    string m_name;
    Phone m_Phone;  //Phone和Game谁在前面先构造谁,跟类位置无关
    Game m_Game;

    void PlayGame()
    {
        cout << m_name << "使用《" << m_Phone.m_name << ">>玩着《" << m_Game.m_name << "》游戏" << endl;
    }
};



void Test201()
{
    Person p1("张三", "华为", "漫威");
    p1.PlayGame();
}

int main()
{
    Test201();
    system("Pause");
    return 0;
}

结果:

原文地址:https://www.cnblogs.com/yifengs/p/15166269.html