Accessing Member Values from Static Member Function
May 26, 2010 at 9:24am UTC
Is there a way to access the value of a member variable from within a static member function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
class MyClass
public :
MyClass();
~MyClass();
static void *Print();
private :
string hello;
};
MyClass::MyClass()
{
hello = "Hello World" ;
}
...
void *MyClass::Print()
{
cout << hello << endl; // Trying to access data stored in "hello" variable
}
The tutorials that I have read say that static functions can only access static members. Here's one of the tutorials:
http://msdn.microsoft.com/en-us/library/yyh8hetw.aspx
So I would have to declare my member variable like this:
1 2 3 4 5 6 7 8 9 10
class MyClass
public :
MyClass();
~MyClass();
static void *Print();
private :
static string hello;
};
string MyClass::hello = "Hello World" ;
But I want to be able to change the value of "hello" from within the class. I have tried the following two methods that don't work:
1 2 3 4
MyClass::MyClass()
{
string MyClass::hello = "Hello World" ;
}
1 2 3 4 5 6 7 8 9
int SetString()
{
string MyClass::hello = "Hello World" ;
}
MyClass::MyClass()
{
SetString();
}
But both return this error:
error: invalid use of qualified-name ‘MyClass::hello’
May 26, 2010 at 9:32am UTC
Static method may have access only to static members
May 26, 2010 at 10:16am UTC
Deluge wrote:The tutorials that I have read say that static functions can only access static members.
So how do I create a static member and change its value from within a class?
May 26, 2010 at 10:57am UTC
I think what ur trying to do is to access a normal variable that can differ per class with a static function. But that's not where static functions are for, you need a regular class function for that.
May 26, 2010 at 1:18pm UTC
http://ubuntuforums.org/showthread.php?p=9362621
Got figured out what I wanted to do:
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
#include <iostream>
using namespace std;
class MyClass
{
public :
MyClass();
~MyClass();
void SetString();
private :
static string hello;
};
string MyClass::hello("Hello World" );
MyClass::MyClass()
{
SetString();
cout << hello << endl;
}
MyClass::~MyClass()
{
}
void MyClass::SetString()
{
hello = "Hello World" ;
}
int main()
{
MyClass test;
return 0;
}
Last edited on May 26, 2010 at 1:23pm UTC
Topic archived. No new replies allowed.