String static members

Asked

Viewed 150 times

2

I’m trying to create a static member in a class so you don’t have to instantiate the class to get the value of the class.

In the examples I found on the internet makes references to members int.

In my case I want the static member to be a string.

If I do this:

class algumacoisa
{

public:
 algumacoisa();
~algumacoisa();

string texto;
static string recebetexto;

};

texto = "alguma frase aqui...";
string algumacoisa::recebetexto = texto;

The following error message appears:

error: Qualified-id in declaration before ?=' token

It is only to illustrate that if you assign a normal string variable to a static string variable the error described occurs. The code is not complete, but you can get an idea of what it refers to.

  • 1

    Put the code you are doing, even because the explanation is confused.

  • Format the code better. I couldn’t even understand to format your question.

  • What code is that?

1 answer

2


Examples made anyway can have all kinds of problem. I did a right and no problem at all.

#include <iostream>
using namespace std;

class AlgumaClasse {

public:
    static string recebetexto;
};

string AlgumaClasse::recebetexto = "alguma frase aqui...";

int main() {
    cout << AlgumaClasse::recebetexto;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Bigown, this way works. But if the phrase is in another variable that is not static and you try to assign this variable to a static variable an error occurs.

  • But @L.Hora, a non-static variable cannot be assigned to a static by the very nature of being static. Also, you can please edit the question with the updated version of your code already using the suggestion of the bigown.

  • Hello Pablo, I was able to solve the issue of assigning a non-static string to a static one. I created a static function that takes a string as argument and within that function I was able to assign this argument to a static string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.