Archived

This topic is now archived and is closed to further replies.

Marty666

Definition problem :(

Recommended Posts

hello! I''ve got a little problem that you probably all know to fix, since I''m pretty new with c++. I have defined a type struct and a class... In the class I use this type, but in the type struct constructor the class is given in the parameters. My problem: Either the class doesn''t know the type or the type doesn''t know the class Marty

Share this post


Link to post
Share on other sites
Just some advice:
It sounds like you are attempting to create member functions for a structure. If you find yourself doing this, consider making the structure a class. Overloading operators is an exception to this rule.
You might want to reconsider your design if you come across a, "chicken or the egg" scenario. Think in terms of how the objects relate. Does one use the other? Only in very rare cases would two classes require mutual access.
However, it is possible to do what you have described. I believe the following code is what you were attempting:

// A Strucure with a member function is a bad idea.
// Overloading an operator for a structure is ok.
struct MyStruct {
MyStruct(class CFoo &);
virtual ~MyStruct();
};

MyStruct::MyStruct(class CFoo &rFoo)
{
}

MyStruct::~MyStruct()
{
}

class CFoo {
public:
CFoo();
virtual ~CFoo();

private:
// Allows MyStruct to access Private data.
friend class MyStruct;
MyStruct *pMs;
};

CFoo::CFoo()
{
pMs = new MyStruct(*this);
}

CFoo::~CFoo()
{
if (pMs)
delete pMs;
}

// End of code.

Again, seriously reconsider your design. This code should be used as a last resort. Classes that use one another is a sign of relationship issues. When designing classes, think in terms of, "Has a" or "Is a" relationships. Hope this helps.

Share this post


Link to post
Share on other sites