Ryan Brown
Ryan Brown

Reputation: 1095

Overloading << for a string class

I have:

String8& operator<<(const String8& string2);

For this:

String8 s;
s << "533";

But I would like to do this:

String8* s;
s << "433";

Without having to do * s << "433"; or String8&. String8* operator<<(const String8& string2); doesn't appear to work. I tried making it a global operator overload too...

Any ideas?

Here is the full code with the operator as global:

class String8 
{
    public:
        String8(char array[]) { }
};

String8* operator<<(String8* string1, const String8& string2);

main()
{
    String8* s;
    s << "433"
}

Compiler error:C2296: '<<' : illegal, left operand has type 'Base::String8 *'

Upvotes: 0

Views: 87

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 186108

You need to make it a non-member function and take a String8* as the first parameter:

String8* operator<<(String8* target, const String8& string2);

BTW, this seems like a rather questionable thing to do just to spare yourself a single asterisk.

Upvotes: 2

Related Questions