class in class

hi.
I have a problem with that code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

class A{public:
	int i;
	class C{public:
		void ctest()
		{
			cout<<"C test()\n"; 
			cout<<i<<endl;
		};
	} c;
};

int main(){
	A a;
	return 0;
}


the problem is with cout<<i<<endl;
how to use i in class A::C ?
can any one help me please ?
sorry for my poor english.
You can do something like this, but remember static member is common to all class instances so please make sure that this is what you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

class A{
public:
	static int i;
class C{
public:
		void ctest()
		{
			cout<<"C test()\n"; 
			cout<< i<<endl;
		};
	} c;
};

int A::i=0;

int main(){
	A a;
	a.i=1;
	a.c.ctest();
	return 0;
}
I have only one object of class A so it will be fine.
Thank You.
Using static is not a good idea.

All you need to do is have an A* in C and use that pointer to get at the i.

When you create a C object you will need to create an A object that has the i in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A{public:
	int i;
	class C{public:
	    A* obj;
		void ctest()
		{
			cout<<"C test()\n"; 
			cout<<obj->i<<endl;
		};
	} c;
};

int main(){
	A a;
	return 0;
}
That is again a good suggestion for class dependencies ,
Thank you!
something like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

class A
{
	public:
	A():
		c(this),
		i(0)
	{};
	int i;
	class C
	{
		public:
		C(A*a){obj=a;};
		A* obj;
		void ctest()
		{
			cout<<"C test()\n"; 
			cout<< obj->i<<endl;
		};
	};
	C c;
};

int main(){
	A a;
	a.i=1;
	a.c.ctest();
	return 0;
}

if I understand correct.
It work.
Than You.
Topic archived. No new replies allowed.