c++ - Error with const string member : no appropriate default constructor available -
i getting no appropriate default constructor available
error following simple piece of code:
class { public: const string cs ; }; void main() { a; return; }
if remove const
string code compiles fine. can not understand why default constructor
not getting created compiler? , deal const string
member variable? working on vs2008.
as mentioned in comments, const
variables cannot left unitialized in c++. there 2 ways can initialize variable. in both cases, content of string can never modified (as const
means).
one: in class declaration. method useful if want string have same value across of objects. inflexible , if find using should declare variable static
.
class { const string cs = "value of cs"; };
alternatively, assign in constructor, using special syntax const
member initialization. more flexible , idiomatic.
class { const string cs; public: a() : cs("value of cs") { } };
note can used arguments, eg
a(string s) : cs(s) //initializes cs value of s
your error arises compiler trying find second option.
Comments
Post a Comment