I would like the following code to be equivalent:
f = "abc";
h.data = f;
EDIT: I’d also like the ability to do the following:
f += "def"; // f.data == "abcdef";
std::string s = f; // s = "abcdef";
std::cout << f << std::endl;
std::cin >> f;
std::vector<std::string> v (f);
v.push_back(h);
// This would be overkill.
printf("%s", (f + std::string("...\n")).c_str());
Would I need to “inherit” std::string or something? (I’m new to this stuff, so could you show me how?)
Here’s my class:
class Foo
{
public:
std::string data;
} f, h;
[ This would have been better served as a new question but I don’t think you could have foreseen that. ]
No, you don’t need to inherit from
std::string. One possible way to do what you want is to add a conversion operator. (I won’t address how to implementoperator+=, it can be looked up elsewhere.)This will do what you want. But I strongly advise you not to use that. Surprising implicit conversions are frowned upon; I recommend reading Herb Sutter to learn why.
Alternatively you can make the conversion operator
explicit(as in, declaring itexplicit operator std::string const&() const;) to suppress implicit conversions. But that’s quite less convenient and readable than adding a member function with an appropriate name:Whatever you choose, I still recommend implementing appropriate operators for working with streams: