Need help on operator overloading in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Need help on operator overloading in c++

Write a c++ program to overload '+' operator to find the sum of length of two given strings. If S1 and S2 are strings then S1+S2 should give the sum of lengths of S1 and S2

10th Sep 2019, 12:23 PM
Manjit Kumar
Manjit Kumar - avatar
9 Answers
+ 3
Sum.h file: #ifndef SUM_H #define SUM_H #include<iostream> using namespace std; class sum {    public:        string s1;        sum(string s1);        int operator+(sum); }; #endif // SUM_H Sum.cpp file: #include "sum.h" sum::sum(string s1) {     this->s1=s1; } int sum::operator+(sum s) {     int n1=s1.length();     int n2=s.s1.length();     return n1+n2; } Main.cpp file: #include <iostream> #include <string> #include "sum.h" using namespace std; int main() {     sum s2("hoytr");     sum s("hi");     cout<<s2+s; return 0; }
10th Sep 2019, 12:59 PM
KfirWe
KfirWe - avatar
+ 1
Output is 7.
10th Sep 2019, 12:59 PM
KfirWe
KfirWe - avatar
0
KfirWe thanks man
10th Sep 2019, 1:01 PM
Manjit Kumar
Manjit Kumar - avatar
0
Manjit Kumar No prob
10th Sep 2019, 1:02 PM
KfirWe
KfirWe - avatar
0
KfirWe while including sum.h in main file ide is not suggesting sum.h it suggest main.h and even after writing sum h it gives error cannot open source file
10th Sep 2019, 1:50 PM
Manjit Kumar
Manjit Kumar - avatar
0
Manjit Kumar There's no main.h Just the cpp file
10th Sep 2019, 2:23 PM
KfirWe
KfirWe - avatar
0
KfirWe i was created a console application in visual studio . And vs created a main.h
10th Sep 2019, 3:24 PM
Manjit Kumar
Manjit Kumar - avatar
0
Manjit Kumar I perssonaly use code blocks not visual studio. Maybe that is the problem?
10th Sep 2019, 3:28 PM
KfirWe
KfirWe - avatar
0
KfirWe let me check on code block
10th Sep 2019, 4:07 PM
Manjit Kumar
Manjit Kumar - avatar