Question
Need help with C++! I'm trying to overload the '+' operator in order to add two strings. For example, if the first input is ###
Need help with C++!
I'm trying to overload the '+' operator in order to add two strings. For example, if the first input is "###" and the second input is "%%%", the result should be "HHH" because '#' has an ASCII value of 35 and '%' has an ASCII value of 37. So, 35+37 = 72. 72 --> ASCII --> H.
I was able to get this code working and so far, but I'm only able to add characters. So, when I input '#' and '%', I get "H". Could someone help me alter this code to work with strings so that I can input "###" and "%%%" and get "HHH"? Also, say the inputs are "hello" and "HELLO". When you add h and H, the resulting ASCII value is 176, which is out of the ASCII table bounds. So, in that case, we can subtract 'z' from the result. So, 176 - 122 = 54. So, h+H = 6.
Here is an ASCII Table for reference: http://www.asciitable.com/
Here is my code that works so far:
#include
using namespace std;
class Strings { //everything is public public: char str; //empty constructor Strings(); Strings(char); //operator takes in an object of Strings Strings operator+(Strings); };
Strings::Strings() {}
//constructor Strings::Strings(char a) { str = a; }
//aso is "another Strings object" //makes new empty object "brandNew" //brandNew is the two characters added together //returns object brandNew Strings Strings::operator+(Strings aso) { Strings brandNew; brandNew.str = str + aso.str; return brandNew; }
int main() { Strings a('#'); Strings b('%'); Strings c; //now, we can use + operator to add characters c = a + b; cout << c.str << endl; return 0; }
Thank you for your help!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started