Trying to access a class within a namespace

Hello.

I'm trying to organize all of my classes into a form of large class or namespace I can create all of my objects with, and to organize groups of classes. Here's some example code:

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
#include <iostream>
#include <math.h>
#include <stdlib.h>

class green
{
public:
	static int a;
};

int green::a = 4;



namespace apple
{
	class green;

};

int main()
{
	std::cout << apple::green::a;
	std::cin.get();
	exit(0);
}


essentially I'm trying to make a class called "green", and try to access it to create objects or to access static variables within it's own namespace. So I can access the static variable a that's in the "green" class which is in the namespace "apple", like 'apple::green::a' or something like that, then if I want to create an object with the 'green' class I would type 'apple::green GrnApple;'.

When I run the above code in MS Visual C++ 2010 I get these errors:

1>------ Build started: Project: class_namespace_test, Configuration: Debug Win32 ------
1> main.cpp
1>error C3083: 'green': the symbol to the left of a '::' must be a type
1>error C2039: 'a' : is not a member of 'apple'
1>error C2065: 'a' : undeclared identifier
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I've seen elsewhere You have to define your class and it's members withing the namespace itself, is that so? or can I have it outside of where I declare the namespace like I have it? Please help.
I've seen elsewhere You have to define your class and it's members withing the namespace itself, is that so?

Yes, a class green in global namespace and a class green in the apple namespace are different classes. If they weren't, that would defeat the purpose of namespaces.
Oh, ok. I was trying to better organize my code. is there a way to make the green class both global and within a namespace with just one declaration? also, if I have a function in the green class, do I have to define it within the namespace as well along with the class? I was trying to have one file with all of my classes then just put them within a namespace to allow access to them that way, through the apple namespace.
is there a way to make the green class both global and within a namespace with just one declaration?
You can use typedef for that. Although it sounds more like you're looking for the using directive.

also, if I have a function in the green class, do I have to define it within the namespace as well along with the class?
Yes. You can also write apple::green::function instead of placing the definition in a namespace block.
Topic archived. No new replies allowed.