Const members of type string in a class definition

U

usenet

Kindly pardon my ignorance, but what is the way to declare a constant
attribute of type string within a class?

Thanks,
Gus
 
R

red floyd

Kindly pardon my ignorance, but what is the way to declare a constant
attribute of type string within a class?

Thanks,
Gus

#include <string>
class C {
const std::string a_const_string;
};

std::string C::a_const_string("Some string value here");
 
R

red floyd

red said:
#include <string>
class C {
const std::string a_const_string;
};

std::string C::a_const_string("Some string value here");


Damn. That should be static const in the declaration , and const in the
definition.

class C {
static std::string const a_const_string;
};

std::string const C::a_const_string("A const string);

.....

Alternatively, if the const is per-object, rather than across the entire
class:

class C {
const std::string a_const_string;
public:
C(const std::string& s) : a_const_string(s) { }
};
 
O

Old Wolf

Kindly pardon my ignorance, but what is the way to declare a constant
attribute of type string within a class?

class C
{
std::string const s;

public:
C(): s("whee") { }
};

As floyd noted, if the string is going to be the same for all objects
of this type, then you could make the compiler's job easier by
making the string static.
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top