two string addition by function overload

plz correct the program
in this program i'm adding two strings by using binary addition operator(+)by function overloading.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#include<conio.h>
#include<string.h>
#include<iostream.h>
class String
{
private:
	char str[40];

public:
      void menu()
      {
      gotoxy(30,12);
	cout<<"Menu";
	gotoxy(30,14);
	cout<<"1.Comparing Strings";
	gotoxy(30,16);
	cout<<"2.Add to Strings";

      }
       void getdata()
	{
	    cin.getline(str,40);
	}
	int operator ==(String i)
	{
	if(strlen(str)==strlen(i.str))
       return 1;
       else
       return 0;
	}
String operator+(String ob)
              {
                            String t;
			    t.str=str+ob.str;
                            t.str=str+ob.str;
                            return(t);
              }
};
void main()
{
 String a,b,c;
 char ch;
 clrscr();
a.menu();
 ch=getch();
 clrscr();
 gotoxy(30,12);
 cout<<"Enter first string";
 a.getdata();
 gotoxy(30,14);
 cout<<"Enter second string ";
 b.getdata();
 clrscr();
 switch(ch){
	case'1':
       if(a==b)
       {
       gotoxy(30,14);
	cout<<"string are equal";
	}
	 else
	 {
	 gotoxy(30,14);
	 cout<<"string are not equal";
	 }
	 break;
	case'2':
       c=a+b;
cout<<c;
       break;
 }
	 getch();
}
I'm lazy right now so I will just give you a general example you can use. If you are going to overload + then you might as well overload += as well because you can use the += in your +.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
struct String
{
	String(string s)
	{
		str = s;
	}

	String& operator+=(const String& rhs) 
	{
	   str += rhs.str;
	   return *this;
  	}

	const String operator+(const String& rhs) const
	{
		String sum = *this;
		return sum += rhs;
  	}

	string str;
};


int main()
{

	String s1("this");
	String s2(" is");
	String s3(" war!");

	s1 += s2;
	s1 += s3;

	cout << s1.str;

	return 0;
}
If you're not referring to the string class in C++, but character strings in general, an easy approach would be declaring a new cstring, copying the first string into the newly created cstring, then concatenating the latter with the second string, and finally returning the resultant cstring. All within the body of the operator. Functions that might help, strncpy(), and strcmp().
Topic archived. No new replies allowed.