Function default parameter

T

The Doctor

Hi,

I have a function, with a default parameter. The code won't compile, and
spits out the following error message:

test.cpp:12: error: invalid use of non-static data member
‘testclass::m_text’
test.cpp:7: error: from this location

Does anyone know a workaround for this problem?

#include <iostream>
using namespace std;

class testclass
{
public:
void function(char* text = m_text)
{
cout << text << endl;
}

char* m_text;
};

int main(int argc, char* argv[])
{
testclass test;
test.m_text = ", world!";
test.function("Hello");
test.function();

return EXIT_SUCCESS;
}

Grtz,

Leon
 
W

WANG Cong

The said:
Hi,

I have a function, with a default parameter. The code won't compile, and
spits out the following error message:

test.cpp:12: error: invalid use of non-static data member
‘testclass::m_text’
test.cpp:7: error: from this location


"a non-static member shall not be used in a default argument expression"
Does anyone know a workaround for this problem?

Yes, make 'm_text' static.
 
T

The Doctor

"a non-static member shall not be used in a default argument expression"



Yes, make 'm_text' static.

Oh i didn't mention that i don't want to make m_text static xD

Any other workarounds?

Grtz,
Leon
 
R

Rolf Magnus

The said:
Oh i didn't mention that i don't want to make m_text static xD

Any other workarounds?


How about:

void function(char* text = 0)
{
if (!text)
text = m_text;

cout << text << endl;
}
 
R

red floyd

The said:
Oh i didn't mention that i don't want to make m_text static xD

Any other workarounds?

class testclass
{
public:
void function(char* text)
{
cout << text << endl;
}
void function()
{
function(m_text);
}

char* m_text;
};
 
D

Daniel Pitts

The said:
Hi,

I have a function, with a default parameter. The code won't compile, and
spits out the following error message:

test.cpp:12: error: invalid use of non-static data member
‘testclass::m_text’
test.cpp:7: error: from this location

Does anyone know a workaround for this problem?

#include <iostream>
using namespace std;

class testclass
{
public:
void function(char* text = m_text)
{
cout << text << endl;
}

char* m_text;
};

int main(int argc, char* argv[])
{
testclass test;
test.m_text = ", world!";
test.function("Hello");
test.function();

return EXIT_SUCCESS;
}

Grtz,

Leon

class testclass
{
private:
char *m_text
public:
void function(const char * const text) const
{
std::cout << text << std::endl;
}
void function() const { function(m_text); }
};
 

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

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top