views:

46

answers:

3
+1  Q: 

Overload binary +

Hello,

I have abstract class:

#include <string>

using namespace std;

class AString
{
    public:
        virtual ~AString() {}

        virtual const string& GetName() const = 0;
        virtual const string& GetValue() const = 0;
        virtual const int GetSize() const = 0;
};

And derivative class. I try to overload binary + in this class:

class SymbString : public AString
{
    private:
        string name;
        string val;

    public:
        SymbString() {}

        SymbString(string _name) : name(_name) {}

        SymbString(string _name, string _val) : name(_name), val(_val) {}

        const string& GetName() const { return name; }

        const string& GetValue() const { return val; }

        const int GetSize() const { return val.size (); }

        const string& SetValue(string value) 
        {
            val = value;
            return val;
        }

        SymbString operator + (const SymbString &str1, const SymbString &str2)
        {

        }

};

But see error: SymbString operator + (const SymbString &str1, const SymbString &str2) must take either zero or one argument

What's wrong?

Thank you.

+2  A: 

You need to put it into SymbString's enclosing namespace. Not as a member.

Or as a member but then only specifying the right parameter. But then "Hello" + symb won't work anymore, because the left side is not a SymbString. So it's advisable to write it as a non-member in SymbString's namespace.

Note that to be able to say symb + "Hello" or the other way around or even writing SymbString s = "Hello";, you also need to accept a char const* as a constructor parameter. Otherwise, a char const* won't be implicitly convertible to a SymbString because that will require to first converting to std::string and then converting from that to SymbString. Two such user defined conversions are not allowed in a single implicit conversion sequence.

Johannes Schaub - litb
Yes, it's in SymbString, i write so in stackoverflow for understandability
shk
+1  A: 

You're defining it as an instance method. This means that the left operand will be the receiver (this) and the right operand will be the argument to the function.

If you want both operands to be arguments, you need to define the method as static, or as function outside of the class.

sepp2k
+1  A: 

I'm guessing you are trying to introduce operator+ as a member function of the class. That's wrong. Define it as a free function. Or have operator+= as a member and implement free function operator+ through that.

Nikolai N Fetissov