Subclassing std::string confusion?

P

petertwocakes

Hi

class StringSubClass : public string {
public:
StringSubClass();
StringSubClass(const char* v) : string(v) {} // casting constructor
virtual ~StringSubClass(){};
StringSubClass& operator=(const string& str) { return
(StringSubClass&)this->assign(str); }

};

If I don't have the casting constructor, then
StringSubClass str = "abc";
fails;

If I don't have the operator=, then
StringSubClass str;
str = "abc";
fails;

But, if I have them both I get the error:
ambiguous overload for 'operator=' in 'sub = "abc"'

How can I define it such that all of the following work?

StringSubClass subStr = "abc";
subStr = "abc";
string stdStr;
StringSubClass subStr2 = stdStr;
subStr2 = stdStr;

I've tried many permutations, but at least one always fails for either
having no definition, or ambiguous overload.

Thanks
 
B

Balog Pal

petertwocakes said:
But, if I have them both I get the error:
ambiguous overload for 'operator=' in 'sub = "abc"'

so make another overload of = to take const char *.
 
P

petertwocakes

so make another overload of = to take const char *.

Many thanks Balog, this works now.

class StringSub : public string
{
public:
// Constructors
StringSub();
StringSub(const char* ch) : string(ch) {}
StringSub(const string& str) : string(str) {}
virtual ~StringSub(){};
//-- Operator"="
StringSub& operator=(const string& str) { return (StringSub&)this-
assign(str); }
StringSub& operator=(const char* ch) { return (StringSub&)this->assign
(ch); }

....

}
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top