*
:
> #include <iostream.h>
Note: this is a non-standard header. Some compilers lack this header. You should use
#include <iostream>
which is a standard header.
> class Cat
> {
> public:
> static HowManyCats;
> private:
> int itsage;
> };
>
> int Cat::HowManyCats=5;
>
> int main()
> {
> cout<<"HowManyCats="<<Cat::HowManyCats<<endl;
> }
>
> The above is right, but the below is wrong, why cannot I declare
> static data member in the class which it belong to?
>
>
> #include <iostream.h>
>
> class Cat
> {
> public:
> static int HowManyCats;
> private:
> int itsage;
> };
>
> Cat::HowManyCats=5;
This definition lacks a type.
> int main()
> {
> cout<<"HowManyCats="<<Cat::HowManyCats<<endl;
> }
>
>
> The following is still not true, why? can I declare the static member
> inside the main function? And if I remove the int from the int
> Cat::HowManyCats=5;statement, it passed the compile, but still blocked
> when building, can anybody explain this for me?
> #include <iostream.h>
>
> class Cat
> {
> public:
> static HowManyCats;
> private:
> int itsage;
> };
>
>
> int main()
> {
> int Cat::HowManyCats=5;
> cout<<"HowManyCats="<<Cat::HowManyCats<<endl;
>
> }
When you remove the 'int' in the code above you have an expression instead of a
declaration. An expression followed by a semicolon is a valid C++ statement. For
example,
42;
is a valid C++ statement where the value of the expression is discarded.
You should up your compiler's warning level so that it warns about statements
with no effect.
With g++ you can do that with '-Wall', with Visual C++ you can do that with '/W4'.
You get a link error because in this latest code there is no definition of
'Cat::HowManyCats'.
It has been declared but not defined.
Cheers & hth.,
- Alf