By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,613 Members | 1,890 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,613 IT Pros & Developers. It's quick & easy.

global variable

P: n/a
Hello,

I have :

class Test
{
public:
Test();
~Test();
void SetTest();
private:
int m_Test;
};

Test::Test()
{
m_Test = NULL;
}

void Test::SetTest()
{
m_Test = n;
}
then :

int n;
int main(int argc, char* argv[])
{
n = 2;

Test* pc = new Test;
return 0;
}
I get :
m_Test = n; =error C2065: 'n' : undeclared identifier
which is normal.

How could I make it working without adding n as parameter to constructor ?

Thanks in advance.
Jun 19 '07 #1
Share this Question
Share on Google+
4 Replies


P: n/a
henri wrote:
Hello,

I have :
Add:
extern int n; // should be in a header file.
class Test
{
public:
Test();
~Test();
void SetTest();
private:
int m_Test;
};

Test::Test()
{
m_Test = NULL;
}

void Test::SetTest()
{
m_Test = n;
}
then :

int n;
int main(int argc, char* argv[])
{
n = 2;

Test* pc = new Test;
return 0;
}
I get :
m_Test = n; =error C2065: 'n' : undeclared identifier
which is normal.

How could I make it working without adding n as parameter to constructor ?
What are you trying to do - there is probably a better way.
Jun 19 '07 #2

P: n/a
henri wrote:
Hello,

I have :

class Test
{
public:
Test();
~Test();
void SetTest();
private:
int m_Test;
};

Test::Test()
{
m_Test = NULL;
See FAQ 10.6, please. Also, using 'NULL' is not a very good
idea, why did you choose it over a simple 0?
}

void Test::SetTest()
{
m_Test = n;
'n' is unknown here.
}
then :
When?
>
int n;
int main(int argc, char* argv[])
{
n = 2;

Test* pc = new Test;
return 0;
}
I get :
m_Test = n; =error C2065: 'n' : undeclared identifier
which is normal.

How could I make it working without adding n as parameter to
constructor ?
To constructor? To which constructor? Didn't you mean "to the
'SetTest' function"?

You need to let the compiler know what 'n' you mean. The easy
way is to declare it right before the 'Test::SetTest' function
definition:

extern int n;

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 19 '07 #3

P: n/a
Gianni Mariani wrote:
What are you trying to do - there is probably a better way.
Thanks to all, I think "extern" will be sufficient.
I just wanted to re-use many global variables, filled at program
startup, in an exiting class function.
Jun 20 '07 #4

P: n/a
Gianni Mariani wrote:
What are you trying to do - there is probably a better way.
Thanks to all, I think "extern" will be sufficient.
I just wanted to re-use many global variables, filled at program
startup, in an existing class function.
Jun 20 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.