Hello. I'm teaching myself how to program in C++ using a book and online resources such as this site. I've written my first program. It is functional with no bugs remaining that I'm aware of, but there were a few issues I ran into during development that I would like to understand better. This one has to do with string assignment statements.
The following code works in its present form. It appends the input file name from the command line (from the argument string passed to main, argv[i] in the snippet below) to an output directory name to make a complete output file name.
1 2 3 4 5 6 7 8 9 10 11
char *dest; // pointer to output directory name
char *pch; // a temporary char pointer
string outfile; // complete output directory and file name
outfile = dest;
if (outfile.at(outfile.size()-1) != '/')
outfile += "/";
if (pch = strrchr(argv[i],'/'))
outfile += (pch + 1); // append input file name to output directory
else
outfile += argv[i];
When I was testing this, I found that there were several other ways I could append the input file name to the output directory name in line 9 above.
All of the following also worked for line 9:
outfile.append(pch + 1);
outfile += pch + 1;
outfile = outfile + (pch + 1);
The following, although it looks very similar to the others, did not work.
outfile = outfile + pch + 1; // does NOT work!
It resulted in a cryptic (for me) compile error that I don't understand:
error: no match for'operator+' in 'std::operator+(const std::basic_string<_CharT, _Traits, _Alloc>&, const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>](((const char*)pch)) + 1'
It looks to me like it should do the same as the other working assignment statements. What makes it different from the ones that worked?
I didn't know at first what you meant by operator+. I read several explanations of operator overloading. My understanding now is that assignment, binary, compound, and comparison operators can be overloaded for a class with functions that have specific behavior depending on the type of the arguments. An overloaded operator is a syntactical substitution for a function call.
I now see why the expression with (pch + 1) works and why the one without parentheses doesn't. There is no overloaded string function for operator+ that takes an integer argument, as you said.
This expression with operator+= works without parentheses:
outfile += pch + 1;
There is a string function, operator+=(const char *), that takes a single operand, so the expression is equivalent to operator+=(pch + 1). The pch + 1 is evaluated and the result is what is sent to the function as the const char * operand.