Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Subclassing std::string confusion?

0 views
Skip to first unread message

petertwocakes

unread,
Nov 28, 2009, 7:04:23 AM11/28/09
to
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

Balog Pal

unread,
Nov 28, 2009, 7:28:14 AM11/28/09
to
"petertwocakes" <petert...@googlemail.com>
> 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 *.


petertwocakes

unread,
Nov 28, 2009, 8:03:37 AM11/28/09
to
On 28 Nov, 12:28, "Balog Pal" <p...@lib.hu> wrote:
> "petertwocakes" <petertwoca...@googlemail.com>

>
> > 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 *.

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); }

...

}

0 new messages