2

当我尝试做这样的事情时,我经常收到这个错误

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

编译器告诉我

error C2110: '+' : cannot add two pointers

但是,如果我将其更改为下面的内容,它可以正常工作吗?

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

GetSystemPath如果与它有任何关系,该函数将返回一个 LPCTSTR

4

4 回答 4

5

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.

于 2013-05-01T19:07:45.157 回答
4

那么你不能添加两个指针。原因filePath += "test.bmp";是左侧是 CString 而不是指针。这也可以

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

这也是

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

除非至少有一个参数是类类型,否则 C++ 的规则会阻止您重载运算符。因此,任何人都不可能只为指针重载 operator+。

于 2013-05-01T19:08:22.927 回答
2

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";
于 2013-05-01T19:08:00.920 回答
0

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" );
于 2013-05-01T19:07:44.820 回答