-3

I have code like below and I need to write a global function overloading the addition operator for objects of this class so that the resulting object represents the concatenation of two strings separated by the '+' sign. Can someone help me?

class A {
    char* str;
    // ...
};
  • Have you read https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading? Then try implementing `operator+` for your class. – cigien Jul 01 '20 at 22:37
  • Did you search the internet first? There are many results for "C++ overload operator" – Thomas Matthews Jul 01 '20 at 22:40

2 Answers2

1

Such operator should have access to content of class and to create a new instance of class A which it returns. Assuming there is no public interface to access str such operator have to be a friend function with signature similar to one below

class A {
    char* str;
    // ...

    friend A operator+ (const A& arg1, const A& arg2)
    {
         A temp{arg1};  // assuming that A have a copy constructor

         // perform concatenation of temp and arg2 here

         return temp; 
    }
};
Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
0

Try something like this:

class A 
{
    char* str;
    // ...

public:
    A(const char *s = nullptr) : str(nullptr) {
        if (s) {
            str = new char[strlen(s)+1]);
            strcpy(str, s);
        }
    }

    A(const A &src) : A(src.str) {}

    A(A &&src) : str(src.str) { src.str = nullptr; }

    ~A() { delete[] str; }

    A& operator= (A rhs) {
        A temp{std::move(rhs)};
        std::swap(str, temp.str);
        return *this;
    }

    friend A operator+ (const A& arg1, const A& arg2)
    {
         A temp;
         temp.str = new char[strlen(arg1.str)+1+strlen(arg2.str)+1];
         sprintf(temp.str, "%s+%s", arg1.str, arg2.str);
         return temp; 
    }
};

That being said, you really should use std::string instead of char*:

class A 
{
    std::string str;
    // ...

public:
    A(const std::string &s = "") : str(s) {}

    friend A operator+ (const A& arg1, const A& arg2)
    {
        return A{arg1.str + "+" + arg2.str};
    }
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770