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

2019-07-21 11:02发布

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

标签: c++ string mfc
4条回答
干净又极端
2楼-- · 2019-07-21 11:27

When doing this:

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

You are trying to sum two pointers of type const char*. As the compiler is telling you, there is no overload of operator + that accepts two pointers of type const 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 of operator +) that takes a CString and a const char*, which is why the second example compiles. For the same reason, this would also work:

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

As well as this:

CString filePath = CString(theApp->GetSystemPath()) + "test.bmp";
查看更多
Root(大扎)
3楼-- · 2019-07-21 11:29

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:

CString filePath = CString( theApp->GetSystemPath() ) + CString( "test.bmp" );
查看更多
Summer. ? 凉城
4楼-- · 2019-07-21 11:45

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.

查看更多
一夜七次
5楼-- · 2019-07-21 11:45

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.

查看更多
登录 后发表回答