Click here to Skip to main content
15,948,338 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hello there,

I'm working on a piece of code. I need to access a variable from one class which is declared in another one.

For Example:
C++
Class Sum
{
double time;
}

class Calc
{
static Sum ss; // reference to the Sum class
}

class Settings :: setup()
{
Calc:: ss.time 
}


I had to make sum static in order to aceess the variable but I get an error that says Unresolved external Symbol
public: static class Sum Geo::ss" (?ss@Geo.....bla bla)
Posted
Updated 27-Mar-12 2:31am
v2

1 solution

static variables must defined in a source file (you provided only the declaration). Put, for instance, in the class Calc source file (say "calc.cpp") the variable definition:
C++
Sum Calc::ss;
 
Share this answer
 
Comments
Sumal.V 27-Mar-12 8:21am    
But when I try that and access the variable it still says non static member reference must be relative to a particualr object.
CPallini 27-Mar-12 8:32am    
Please show your actual (current) code.
Sumal.V 27-Mar-12 8:40am    
Well its a massive code, I will show u the main bits.

1) class AFX_EXT_EDATA Sum : public CMainSum
{
double time1;
double time2;
}

2)class AFX_EXT_EDATA Calc
{
Sum Calc :: ss;
}

3) void Settings::SetupCtrls()
{
InsCtrl(80, EC_EDIT, Calc::ss.time2); //I get the error here!
}

This error goes if I declare Sum in calc as static but again gives the unresolved external symbol error!!!
CPallini 27-Mar-12 8:52am    
The following code works:


#include <iostream>

using namespace std;
class Sum
{
public:
double time1;
double time2;
Sum(){time1=0.5; time2=0.7;}
};

class Calc
{
public:
static Sum ss;
};

void SetupCtrls()
{
cout << Calc::ss.time2 << endl;
}

Sum Calc::ss; // STATIC VARIABLE DEFINITION

int main()
{
SetupCtrls();
}
Stefan_Lang 27-Mar-12 12:17pm    
When you write Calc::, then the symbol after that can only be static: either a static member variable, or a type defined in that class, or a function name. static means that you can have as many objects of that class as you like, but you'll only have exactly one value of that static variable. In effect, static means global.

If you want to access a non-static member of a class, you need to have an instance of that class, and then access members of that instance using '.' or '->'. Example:
class Calc {
public:
Sum ss;
};
int main() {
Calc myCalcInstance1; // myCalcInstance1 is one instance of class Calc
Calc myCalcInstance2; // this is another instance; now you have two instances
myCalcInstance1.ss.time1 = 0.1; // access value in first instance
myCalcInstance2.ss.time1 = 2.3; // access value in second instance
return 0;
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900