C++类中的成员可以是另一个类的对象,我们成该成员为对象成员

class A
{};
class B
{
    A a;
};
//B类中有对象A作为成员,A是对象成员
  • 当其他类对象作为本类成员,构造时候先构造类对象,再构造自身
  • 析构的顺序与构造相反
#include <iostream>
using namespace std;
#include <string>
//类对象作为类成员

//手机类
class Phone
{
public:
    Phone(string pname)
    {
        m_pname=pname;
        cout << "Phone 的构造函数" << endl;
    }
    string m_pname;
};

class Person 
{
public:
    //Phone m_phone = pname; 隐式转换法
    Person(string name,string pname):m_name(name),m_phone(pname)
    {
        cout << "Person 的构造函数" << endl;
    }

    //姓名
    string m_name;
    //手机
    Phone m_phone;
};
void test()
{
    Person p("张三","苹果");
    cout << p.m_name << "拿着" << p.m_phone.m_pname << endl;
}
int main()
{
    test();
    system("pause");
    return 0;
}

相关文章:

  • 2022-02-15
  • 2022-12-23
  • 2021-09-14
  • 2021-12-13
  • 2021-09-30
  • 2021-11-30
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-31
  • 2021-08-31
  • 2021-09-16
相关资源
相似解决方案