C++ “cannot add two pointers”, adding a hardcoded string to a CString

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


This has to do with the types of objects that you are dealing with.

CString filePath = theApp->GetSystemPath() + "test.bmp";

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:

filePath += "test.bmp";

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 work

CString(theApp->GetSystemPath()) + "test.bmp";

and so would this

theApp->GetSystemPath() + CString("test.bmp");

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.

Need Your Help

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.