Static Functions and Variables

I am having trouble using static function. I am initialising two static variables in GetResult() Function and then trying to get result using get_ans1() and get_ans2(). All the functions and variables are static. Have a look.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "stdafx.h"
//Exercise 1

#include <iostream>

using namespace std;

class GetResult
{

private:

static double ans1;
static double ans2;


public:

static void GetResultFunc()
{
	ans1 = 1000.0;
	ans2 = 45.0;
}

static double get_ans1()
{
	return ans1;
}

static double get_ans2()
{	
	return ans2;
}

};


int _tmain(int argc, _TCHAR* argv[])
{
	GetResult::GetResultFunc();

	cout<< "\n" << "Answer 1 : "<< GetResult::get_ans1();
	cout<< "\n" << "Answer 2 : "<< GetResult::get_ans2();
	return 0;
}
You need to define the two static data members outside the class.
Also, _tmain isn't standard ( as _TCHAR )
Static variables are class variables, why should they be defined outside the class?
Also see the msdn article : http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx.
I think there might be problem in the Main function..
From your link:
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as conststatic can have an initializer


From http://www.cplusplus.com/doc/tutorial/classes2/ :
In fact, static members have the same properties as global variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization). In order to initialize a static data-member we must include a formal definition outside the class, in the global scope
Topic archived. No new replies allowed.