|
-
April 2nd, 2002, 06:25 AM
#1
Inner class issues
Can any one help me!!!
I have an inner class in the main class. There is some variable declared in main class some thing like this
class MainClass
{
class Inner
{
public :
Display();
};
public:
int x;
Inner inObj;
};
I need to know that is there any way to access x from function display.
-
April 2nd, 2002, 06:46 AM
#2
Re: Inner class issues
Hi,
this will work.
int* ptrToX = ((int*)this) - 1;
But be careful, however it seems to be only way,
it's not a legal way to access data-member, and generally speaking against OO.
In the future computer's weight will not exceed 1.5 ton.
(Popular Mechanics, 1949)
-
April 2nd, 2002, 11:44 AM
#3
Re: Inner class issues
you can access x from Display because it is public in MainClass, but you will also need an instance of MainClass through which to access it, as x is a member of MainClass and not of Inner.
There is not necessarily a one-to-one relationship between MainClass and Inner. While every MainClass has an Inner, the converse is not true - although the class is private, there is nothing to stop any member functions of MainClass creating new ones.
You could, of course, pass in a pointer to the constructor of Inner. You will get a warning, but you can ignore it. Thus:
class MainClass
{
class Inner
{
public :
Inner( MainClass * outer=0) : m_outer(outer) {}
Display();
MainClass * m_outer; // or make it private
};
//
public:
int x;
Inner inObj;
MainClass();
};
//
// MainClass constructor (in MainClass.cxx)
//
MainClass::MainClass()
: inObj( this ) // will raise a warning but ignore it or pragma it out
{
}
The best things come to those who rate
-
April 2nd, 2002, 11:50 AM
#4
Re: Inner class issues
You could try something like:
#include <iostream>
using namespace std;
class MainClass
{
class Inner
{
int& m_x;
public:
Inner( int& x ) : m_x(x)
{
}
void Display()
{
cout << "x = " << m_x << endl;
}
};
public:
MainClass() : inObj(x), x(5)
{
}
int x;
Inner inObj;
};
int main(int argc, char* argv[])
{
MainClass object;
object.inObj.Display();
return 0;
}
This example puts a reference to the x variable into the inner class (which is initialized by the MainClass constructor).
The Display routine then accesses the MainClass::x member by using a reference.
Best regards,
John
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|