I get this error quite often when I try to do something like this
CString filePath = theApp->GetSystemPath() + "test.bmp";
The compiler tells me
error C2110: '+' : cannot add two pointers
But if I change it to this below it works fine?
CString filePath = theApp->GetSystemPath();
filePath += "test.bmp";
The function GetSystemPath
returns a LPCTSTR if that has anything to do with it
When doing this:
You are trying to sum two pointers of type
const char*
. As the compiler is telling you, there is no overload ofoperator +
that accepts two pointers of typeconst char*
s as its input (after all, what you want is not to sum the pointers, but to concatenate the zero-terminated strings pointed to by those pointers).On the other hand, there is an overload of
operator +=
(as well as ofoperator +
) that takes aCString
and aconst char*
, which is why the second example compiles. For the same reason, this would also work:As well as this:
The compiler may not be aware that the programmer is intending to concatenate two strings. it merely sees that a
char const *
is being added with another using the+
operator.I'd try something like this:
This has to do with the types of objects that you are dealing with.
The line above is attempting to add the type of GetSystemPath() with "test.bmp" or an LPCTSTR + char[]; The compiler does not know how to do this because their is no + operator for these two types.
The reason this works:
Is because you are doing CString + char[] (char*); The CString class has the + operator overloaded to support adding CString + char*. Or alternatively which is constructing a CString from a char* prior to applying the addition operator on two CString objects. LPCTSTR does not have this operator overloaded or the proper constructors defined.
Well you can't add two pointers. The reason
filePath += "test.bmp";
works is that the left hand side is a CString not a pointer. This would also workand so would this
The rules of C++ prevent you overloading operators unless at least one of the argument is of class type. So it's not possible for anyone to overload operator+ for pointers only.