• 类A have-a 类B,类B访问类A public 成员


    需求是类A中包含类B,而类B又需要访问类A的public属性的成员。

    首先类B中要访问类A的属性,那么对于类B而言,我们必须要知道有类A这个类,所以在类B的具体实现之前我们需要前向声明类A。

    对于类A包含一个类B的对象,那么对于类A而言,需要知道类B的构造函数,所以类B的构造函数的声明需要在类A的具体实现之前。

    main.cpp

    #if 0//Multi
    #include "A.h"
    #else
    #include <iostream>
    using namespace std;
    
    class CA;
    class CB
    {
        public:
            void funB(CA &a);
            CB(){};
            ~CB(){};
    };
    
    class CA
    {
        public:
            int m_a;
            CB b;
            void funA();
            CA(int a);
            CA(){};
            ~CA(){};
    };
    
    void CA::funA()
    {
        b.funB(*this);
    }
    CA::CA(int a)
    {
        m_a=a;
    }
    
    void CB::funB(CA &a)
    {
        cout<<"this is CA: "<<a.m_a<<endl;
    }
    #endif
    int main()
    {
        CA a(3);
        a.funA();
        return 0;
    }

    多文件的话则选择Multi开关下的代码

    A.h

    #ifndef _A_H_
    #define _A_H_
    #include "B.h"
    class CA
    {
        public:
            int m_a;
            CB b;
            void funA();
            CA(int a);
            CA(){};
            ~CA(){};
    };
    #endif

    A.cpp

    #include "A.h"
    void CA::funA()
    {
        b.funB(*this);
    }
    CA::CA(int a)
    {
        m_a=a;
    }

    B.h

    #ifndef _B_H_
    #define _B_H_
    class CA;
    class CB
    {
        public:
            void funB(CA &a);
            CB(){};
            ~CB(){};
    };
    #endif

    B.cpp

    #include "A.h"
    #include "B.h"
    #include <iostream>
    using namespace std;
    void CB::funB(CA &a)
    {
        cout<<"this is CA: "<<a.m_a<<endl;
    }

    太水了,继续享受着在被我拖着后腿的公司里工作。

  • 相关阅读:
    vue项目使用async await 封装 axios
    vue实现预览功能(包括doc,pdf,图片,视频)
    vue中实现下载文件功能
    vue项目中加入拖放排序功能
    Vue项目中生成二维码
    position跟display、overflow、float这些特性相互叠加后会怎么样?
    localStorage使用注意
    webpack 使用总结
    cookie作用域
    语法糖的理解
  • 原文地址:https://www.cnblogs.com/NoSoul/p/3277233.html
Copyright © 2020-2023  润新知