On 5 Mrz., 10:18, Richard Lee <prodigyn...@[EMAIL PROTECTED]
> wrote:
> The following does compile, but has other problems:
[..]
> The problem is that if you later try to refer to class A, the compiler
> claims it is not a class, it's a namespace. Aren't cl***** by
> definition namespaces? Something seems broken here.
Cl***** are *not* namespaces.
namespace A { int x; } declares and instantiates an int variable with
name x that can be accessed as A::x without further preparation.
#include <iostream>
namespace A { int x; }
int main() {
A::x = 42;
std::cout << "A::x is " << A::x << std::endl;
return 0;
}
class A { public: int x; }; only defines a new type of objects and no
instance at all. Thus, you cannot use A::x e.g. in you main program.
You first need to create an object of type "class A":
#include <iostream>
class A { public: int x; };
int main() {
A obj;
obj.x = 42;
std::cout << "obj.x is " << obj.x << std::endl;
return 0;
}
You can create more objects of type "class A" and each will provide a
new and separate instance of the member variable x.
Note also, you need to reference to x with the "." operator and not
with "::".
You can create member variables which are shared between all instances
of a class and get accessed in a way that looks similar to the
namespace access operator:
#include <iostream>
class A { public: static int x; }
int A::x;
int main() {
A::x = 42;
std::cout << "A::x is " << A::x << std::endl;
return 0,
}
This looks a little more similar to the namespace example but note,
class A is still just a type and A::x needs to be instantiated
separately.
I hope the difference became more clear to you.
best,
Michael


|