2

How can I overload the left shift operator for strings, can someone help me? :

const char*
{
    int operator<<(const char* rhs)
    {
        return std::atoi(this) + std::atoi(rhs);
    }
}

int main() {
    const char* term1 = "12";
    const char* term2 = "23";
    std::cout << (term1 << term2);
}

(above code does not compile)

Expected output: 35

10
  • 3
    C doesn't have support for operator overloading. Don't spam tags Apr 15, 2018 at 11:46
  • 1
    You will never be able to get that code to do what you want - operator overloads must involve at least one user-defined type. Apr 15, 2018 at 11:47
  • Does this even compile? BTW - atoi is crap. Does to check for errors
    – Ed Heal
    Apr 15, 2018 at 11:47
  • @EdHeal No, this won't compile. The OP is asking how to re-write it so that it does compile. :)
    – user743382
    Apr 15, 2018 at 11:48
  • 1
    @achal - It is a shift operator, at least as far as the C++ spec is concerned. Apr 15, 2018 at 11:51

2 Answers 2

5

juanchpanza's answer is right on the money. What you're trying to do can't be done because you're using a built-in type.

However, you can do it with custom types, including std::string.

The following program illustrates how to do it:

#include <iostream>
#include <cstdlib>
#include <string>

auto operator << (std::string a, std::string b) -> int
{
    return std::atoi(a.c_str()) + std::atoi(b.c_str());
}

int main()
{
    std::cout << (std::string("1") << std::string("2"));   
}

It's probably not a good idea to do it however.

6
  • better to use (const string& a, const string& b)
    – gchen
    Apr 15, 2018 at 11:56
  • 1
    You can use std::string_view in C++17, and avoid much the overhead associated here with std::string. Can even make it more readable with the use of the user defined literal for string views. Apr 15, 2018 at 12:04
  • @StoryTeller I can only agree. I'm not going to improve on the answer since I wouldn't recommend doing anything like this in the first place.
    – Clearer
    Apr 15, 2018 at 12:18
  • I can respect that :) Apr 15, 2018 at 12:20
  • 1
    atoi can only be used safely if you already know that the string is parseable as an integer number, or if 0 represents an error anyway. Use std::stoi instead. Apr 15, 2018 at 12:22
3

C++ does not allow overloading operators purely for built-in types. So it is not possible to overload left shift for pointer to const char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.