How can string values be +ed?

I found some examples in the tutorial. which are :


string concatenate (string a, string b)
{
return a+b;
}
------------------------------------
string concatenate (string& a, string& b)
{
return a+b;
}
----------------------------------------

the string variables are not numbers, they are letters in sequence, as I know,
How can + operator process them? I tried to put them in my visual studio, but they didn't work.
The + is an operator and in your example a and b are operands being operated on.
You could think of it this way,
+(string a,string b) or +(int a, int b)
What + means, that is, what operation is intended to take place, is determined by the operands. This is called overloading the operator just as you can overload a function.
If they are strings they are joined. If they are numbers they are added.


#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;

string concatenate(string a, string b) {
return a + b;
}

int main() {
string a,b;
a = "The first string"; b = "The second string";
cout << string;
system("pause");
}

this is the code I tried to see how it works. so it should be joined as your explain, but it just didn't join and didn't work. on what part is it wrong?
Last edited on
You don't call concatenate from main so what is it used for?
cout << string ?????

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<string>
using namespace std;

int main()
{
    string a,b;
    int n1,n2;
    a = "The first string";
    b = "The second string";
    n1 = 5;
    n2 = 6;
    cout << a + b << endl;
    cout << n1+n2 << endl;
return 0;
}

Last edited on
Your code worked good.

but my code was to execute the function concatenate and I wrote string instead of concatenate by mistake, thanks for letting me know that,

I corrected it as :

cout<< concatenate(a,b);
and it worked ! thank you !
by the way, I always put
#include <stdlib.h>
at the very first of my code and
system("pause");
at the end of the code.

it is to stay the console window so that I can look at the result with time.
or it just disappears just right after it appears.

do you guys don't do it?
and I just found it is why my console window process hangs..
Topic archived. No new replies allowed.