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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With