Reputation: 1017
Is there a way to convert a string to a custom class, for example if I have a class named Numb, but I want to declared it as a string with the = operator, can I overload it?
class Numb{
std::string x;
};
int main(){
Numb n = "32";
//Creates a Numb and makes x = "32"
}
Upvotes: 2
Views: 645
Reputation: 306
You want to construct Numbs from a string literal. String literals are indistinguishable from type String literals have type const char *
const char [N]
, which we can take as an argument by writing a function that accepts const char *
.
To define a converting constructor with this behavior, just write a signature like that of a copy constructor, but instead of expecting an argument of the same type, expect an argument of type const char *
. Its signature would look like Myclass(const char *);
Alternatively, you can copy or move construct from strings, but that would require doing Numb n = std::string { "32" };
or similar, to convert the string constant to a std::string.
Here is some sample code, in which main() returns 3. Here we also demonstrate what to do with the value: if we instead did Num n2 = std::string { "TRAP" };
, the code would return 1. If we did Num n2 = std::string { "ANYTHING OTHER THAN TRAP" };
it would return 2.
#include <string>
struct Num {
Num()
: _val(2) {}
Num(const std::string & str) {
if (str == "TRAP") {
_val = 1;
} else {
_val = 2;
}
}
Num(const char * s) {
_val = 3;
}
int _val;
};
int main(void) {
// Num n = std::string { "TRAP" }; // returns 1
// Num n = std::string { "NOTTRAP" }; // returns 2
Num n = "TRAP";
return n._val;
}
EDIT: Fix a mistake re the type system, take the string arg as & not &&, simplify example, update compiler explorer link.
Upvotes: 2
Reputation: 6125
If you make x
a public
member, you can assign to it like this:
class Numb
{
public:
std::string x;
};
int main()
{
Numb n{ "32" };
Numb o = { "33" };
n = { "34" };
o.x = "35";
}
Upvotes: 1
Reputation: 91
Yes, you can using converting constructors. Something like:
struct A {
A(std::string);
// A is a struct, so str is public
std::string str;
};
// implementation for converting constructor
A::A(std::string s) {
str = s;
}
int main() {
A my_a = std::string("hello");
std::cout << my_a.str << '\n';
}
Sometimes you might not want this behavior. You can mark the constructor as explicit
to disable it.
Upvotes: 2