Pergunta

I have a class with a method with the following signature:

void print(unsigned char *word);

I need to set "" as default value for word, how can I do that?

I tried the obvious void print(unsigned char *word=""); but I got the following error:

error: cannot initialize a parameter of type
  'unsigned char *' with an lvalue of type 'const char [1]'
    void print(unsigned char *word="");

Since I can't initialize word with a string literal who should I do it?

Foi útil?

Solução

You say that this is a "prefix" argument to apply to the printing.

The answer is that you should make the argument const, stop doing whatever mutations you're doing to it inside the function, and then use "" as a default argument:

void print(const char* prefix = "")

Outras dicas

try

unsigned char empty[] = { 0 };

void print(unsigned char* word = empty )
{
  ...
}

"" yields an array of const char, whereupon you want an array of or pointer to NON-const unsigned char, both the type and the cv-qualification don't fit.

Note also that in C++ char != signed char and char != unsigned char.

Possibly you mean void print(const char *word);, but probably you want just print(std::string const &) or print(std::string).

 void print();
 void print(unsigned char* prefix);
 // in cpp file:
 void print(){
   unsigned char temp = 0;
   print(&temp);
 }

This provides two overloads, one with 0 and one eith one argument.

The zero argument one has some automatic storage memory it provides to the one argument one. Note that only the single byte under the pointer is valid to read/write: without a length, print has no way to know any different anyhow.

While there is no array, none is needed for a single element.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top