Use of Static Variables from Outside of Defining Class

C

Chris Portka

How can I modify static variables from outside the class they're
defined in? It doesn't work if I try to access them from a function,
from an instantiated object, or from the class itself. Here's an
example:
MAIN:
#include "test"

int main()
{
Test t;
//All of these give "unresolved external symbol"
t.x = 1;
t.setX(1);
Test::x = 1;
Test::setX(1);
}

TEST:
class Test
{
public:
static int x;
static void setX(int z) { x = z; }
};
 
R

Robert Bauck Hamar

Chris said:
How can I modify static variables from outside the class they're
defined in? It doesn't work if I try to access them from a function,
from an instantiated object, or from the class itself. Here's an
example:
MAIN:
#include "test"

put
int Test::x;
about here.
int main()
{
Test t;
//All of these give "unresolved external symbol"
t.x = 1;
t.setX(1);
Test::x = 1;
Test::setX(1);
}

TEST:
class Test
{
public:
static int x;

This is only a declaration. You need a definition too.
 
D

David Harmon

On 5 Dec 2006 16:45:23 -0800 in comp.lang.c++, "Chris Portka"
//All of these give "unresolved external symbol"
t.x = 1;
t.setX(1);
Test::x = 1;

This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[10.11] Why are classes with static data members getting linker
errors?" It is always good to check the FAQ before posting. You can
get the FAQ at:
http://www.parashift.com/c++-faq-lite/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top