开发者

C++ Set object member as reference/pointer of member of a different object?

(I'm not sure if that title is worded correctly, as I'm still new to C++)

I have two classes, loosely represented here:

class SuperGroup
{
public:
    LayoutObj theLayout;
}

class SomeClass
{
public:
    LayoutObj myLayout;
    SuperGroup myGroup;
}

During SomeClass's constructor, I want to set myGroup.theLayout to be pointing to SomeClass's searchLayout. Something like this:

SomeClass::SomeClass()
{
    myGroup.theLayout = &myLayout;
}

Am I doing this correctly? Or do I need to be using a pointer? My code seems to compile okay, but when I execute it, it crashes, and I can tell its something to do with this assignment. Also, I'm not sure if its incorrectly coded, or if the SDK/API I'm using simply doesn't like it.

The reason I'm trying to reference myLayout with SuperGroup is because I have many methods in SuperGroup that need to use myLayout from SomeClass. I'm simply trying to avoid having the pass myLayout by reference int开发者_C百科o those methods every single time. Make sense? Is there an easier way to accomplish this?


You do indeed need a pointer. Try using:

LayoutObj *theLayout;

Without a pointer, you are trying to assign a LayoutObj to a memory address. This may compile, but is not the behavior you want. Instead, you need a pointer to point to the memory address of a LayoutObj.

The line myGroup.theLayout = &myLayout; remains the same.

As always is the case with C++, be careful that myLayout does not go out of scope before theLayout. If this happens, you have a dangling pointer. If there is any risk of this, consider using a smart pointer of some kind, or otherwise modify your design to accommodate this.


Yes, you would need to use a pointer: LayoutObj *theLayout;

In reference to your last paragraph, I would consider the some alternative designs, such as:

  • Requiring that the LayoutObj is passed into each method of SuperGroup, therefore decoupling the particular LayoutObj acted upon from the actions that can be performed, or
  • Moving those methods to SomeClass, if they're not needed elsewhere, or
  • Making them methods of LayoutObj itself.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜