-
April 30th, 2009, 09:36 AM
#1
static
Code:
#include <iostream >
using namespace std;
class CL
{
public:
int x;
static int y;
};
int CL :: y=2;
int main()
{
return 0;
}
Why I can't write it like?
Code:
#include <iostream >
using namespace std;
class CL
{
public:
int x;
static int y=2;
};
int main()
{
return 0;
}
And why in local classes (like class declared in function) I can't use static variables?
Thanks in advance.
-
April 30th, 2009, 11:40 AM
#2
Re: static
C++ doesn't support initializing non const variables in a class declaration. I believe that may change with the next iteration of the C++ standard.
Viggy
-
April 30th, 2009, 11:43 AM
#3
Re: static
const static integers (and related types) may be initialized inline for now.
-
April 30th, 2009, 12:18 PM
#4
Re: static
Thanks for the help. But why it isn't possible? What's the problem?
Thanks in advance.
I got another question. Why I can't use variables other then static variables in static functions?
-
April 30th, 2009, 12:36 PM
#5
Re: static
Originally Posted by StGuru
Thanks for the help. But why it isn't possible? What's the problem?
Thanks in advance.
Because it isn't
I got another question. Why I can't use variables other then static variables in static functions?
Because that doesn't make any sense at all. You first need to make a instance of the class to be able to call its non-static member functions or use its non-static variables. A class is just a template to create objects from, nothing actually exists yet until you make an instance. This is why static content can always only interact with other static content.
Last edited by AlastrionaAdair; April 30th, 2009 at 12:39 PM.
-
May 1st, 2009, 02:00 AM
#6
Re: static
Originally Posted by StGuru
I got another question. Why I can't use variables other then static variables in static functions?
The response above this pretty much sums it up. As soon as you understand what a static member variable/function is, the answer is self-evident. When you declare a member of a class static, you're essentially making it global. Whatever you declare static is going to be the same no matter where in the program you access it from; there's one copy of it.
The class within which you declare it is instantiated as an instance (an object), of which there can be multiple copies. The static member is singular. Therefore, it doesn't make any sense to try to reference something nonstatic within a static context.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|