• Advertisement
Sign in to follow this  

a cpp question

This topic is 3960 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey, I just how to solve this:
class CClassOne
{
private:
CClassTwo classtwo;
int a;
};

class CClassTwo
{
public:
int add_a();//I just want to increase a of CClassOne, how can I do?
};
Thanks!

Share this post


Link to post
Share on other sites
Advertisement
CClassOne is a class. CClassOne::a is not a static variable. Therefore: of which instance of CClassOne do you want to increase the member variable a ?

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
CClassOne is a class. CClassOne::a is not a static variable. Therefore: of which instance of CClassOne do you want to increase the member variable a ?

Sorry, may be I didn't make myself clear enough. I just want to know, if an instance of CClassOne is already exits, say classone. How can classone's data member classone.classtwo's function member add_a() access the data member a in classone.

Share this post


Link to post
Share on other sites
I'm guess he wants it to increase the 'a' member of the same CClassOne parent that the CClassTwo object is a member of...

However, the CClassTwo object does not have that information, as it stands. That means that e.g. if it is a standalone CClassTwo instance, the above comment wouldn't make sense.

jhq: you need the CClassTwo to point to the parent. Something like this.


class CClassOne
{

private:

CClassTwo classtwo(this); // can't quite remember if this is legit. or not
// maybe use a SetParent() function if not.
int a;

};

class CClassTwo
{

public:

int add_a();//I just want to increase a of CClassOne, how can I do?
CClassOne * parent;
CClassTwo(CClassOne * p) { parent = p; } // constructor

};

int CClassTwo::add_a()
{
parent->a++;
return parent->a;
}



Share this post


Link to post
Share on other sites
Incorrect encapsulation. CClassTwo here assumes each of its instances will be owned by a CClassOne instance. This is incorrect, because it is always possible to instantiate CClassTwo on its own, as follows:

CClassTwo myInstance;
myInstance.add_a(); // What does this call do?


Since your instance intends to alter an instance of CClassOne, let that instance be provided. acemuzzy above outlined the basic idea behind this. The actual implementation:

class CClassOne;

class CClassTwo
{
CClassOne & parent;
public:
CClassTwo(CClassOne & parent) : parent(parent) {}
void add_a()
{
++parent.a;
}
};

class CClassOne
{
friend class CClassTwo;
int a;
CClassTwo classtwo;
public:
CClassOne() : classtwo(*this) {}
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement