C++:lower class obj访问upper class obj

前言

首先本篇文章讨论集成,而是一个class 包含另一个class obj,比如下面代码,base class里面包含了derive class的obj

class derive{
public:
	derive(){}
	~derive(){}
};

class base{
public:
	base()
	:d(){
	
	}
	~base(){}
private:
	derive d;
};

那么问题来了,如果class A包含2个class obj,分别是B和C,而C又包含一个class obj D,此时D obj想调用B obj的某个成员函数怎么办?如下图

class A
class B
class C
class D

解决方案

这里建议在class C中传入class B的obj指针到D中如下代码,class B有一个成员函数,而class D的obj想调用它

#include 
class B{
public:
    B(){std::cout << "B construct" <<std::endl;}
    ~B(){std::cout << "B destruct" << std::endl;}
    int get_id(){return id_;} 
private:
    int id_ = 10;

};

class D{
public:
    D(class B *b):b_(b){std::cout << "D construct and  get class B's id " << b_->get_id() <<std::endl; }
    ~D(){std::cout << "D destruct" << std::endl;}
private:
    class B *b_;
};



class C{
public:
    C(class B *b):d(b){std::cout << "C construct" <<std::endl;}
    ~C(){std::cout << "C destruct" << std::endl;}
private:
    class D d;
};

class A{
public:
    A():b(),c(&b){std::cout << "A construct" <<std::endl;}
    ~A(){std::cout << "A destruct" << std::endl;}
private:
    class B b;
    class C c;
};

int main(){
    auto a = new A();
}

你可能感兴趣的:(c/c++,c++)