Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading the left shift operator for strings in C++

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

like image 991
Pascal pizza Avatar asked Apr 10 '26 04:04

Pascal pizza


1 Answers

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.

like image 140
Clearer Avatar answered Apr 28 '26 13:04

Clearer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!