我创建了一个具有Component类,Leaf类和Composite类的复合模式,其中只有Composite类同时具有成员变量vector和add方法:
void add(Component *a);
vector < Component * > children;
在一个单独的类A中,我创建了一个getComponent()方法以返回Composite成员变量
Class A
{
Composite m_Comp;
public:
Component * getComponent()
{
Leaf myLeaf1;
Leaf myLeaf2;
Composite myComp1;
myComp1.add(&Leaf1)
myComp1.add(&Leaf2)
Leaf myLeaf3;
m_Comp.add(&myComp1);
m_Comp.add(&myLeaf3);
// just for checking purposes
Component* mypCompCheck=&m_Comp;
return &m_Comp;
}
};
当我检查mypCompCheck时,它看起来不错,但是当我从main中检索它(?)时:
A* myA;
Component * mypComp=myA->getComponent();
mypComp不是同一对象。我认为退货的方式有误吗?
尝试理解这一点:
int& function_1() {
int q = 5;
return q; //you are not allowed to do this
//when the function scope is ended automatically the q is deleted from stack
//q has automatic storage duration
static int i;
return i; // Safe but not good practice, i lives outside this scope
}