A
alexo
Hello,
I don't know very much about inner classes, I'm still learning
the subject. Playing with the compiler and searching for a solution
on the Web I have written the following code.
In it I successfully try to access a private member of an outer
class from the inside of an inner class. [I do that because of I heard
that inner classes could access outer's data member
either public or private].
I know there are many ways to accomplish the same task in computer
programming especially for languages as powerful and flexible as C++,
so my asking was if there were other methods to accomplish the same
task. Two solutions came to my mind, namely
make the inner class a friend of the outer class
make the inner class to inherit from outer
but both ways I was unable to properly set up.
Could you tell me if these two methods can be successfully be applied?
Thank you.
*cut here*
#include <iostream>
using std::cout;
using std::endl;
class Outer
{
private:
int x; // the member I would like to access from
// Inner class
public:
Outer() {}
~Outer() {}
void show()
{
cout << "the value of x is " << x << endl;
}
class Inner
{
public:
Outer *o;
Inner(Outer * p_out) {o = p_out;}
~Inner() {}
void setx(int val)
{
o->x = val;
}
};
};
int main()
{
Outer A;
Outer::Inner B(&A);
B.setx(3); // set Outer's x to 3
A.show();
return 0;
}
I don't know very much about inner classes, I'm still learning
the subject. Playing with the compiler and searching for a solution
on the Web I have written the following code.
In it I successfully try to access a private member of an outer
class from the inside of an inner class. [I do that because of I heard
that inner classes could access outer's data member
either public or private].
I know there are many ways to accomplish the same task in computer
programming especially for languages as powerful and flexible as C++,
so my asking was if there were other methods to accomplish the same
task. Two solutions came to my mind, namely
make the inner class a friend of the outer class
make the inner class to inherit from outer
but both ways I was unable to properly set up.
Could you tell me if these two methods can be successfully be applied?
Thank you.
*cut here*
#include <iostream>
using std::cout;
using std::endl;
class Outer
{
private:
int x; // the member I would like to access from
// Inner class
public:
Outer() {}
~Outer() {}
void show()
{
cout << "the value of x is " << x << endl;
}
class Inner
{
public:
Outer *o;
Inner(Outer * p_out) {o = p_out;}
~Inner() {}
void setx(int val)
{
o->x = val;
}
};
};
int main()
{
Outer A;
Outer::Inner B(&A);
B.setx(3); // set Outer's x to 3
A.show();
return 0;
}