C++文字和常量之间的串联
我是 C++ 新手,我想知道为什么下面的行不正确。 (SERVER_NAME 已定义为常量)
L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";"
我收到这些错误:
error C2296: '<<' : illegal, left operand has type 'const wchar_t [...'
error C2308: concatenating mismatched strings
谢谢
I am new to C++ and I want to know why the line below is not correct. (SERVER_NAME has been defined as a constant)
L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";"
I get these errors:
error C2296: '<<' : illegal, left operand has type 'const wchar_t [...'
error C2308: concatenating mismatched strings
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
运算符<<不是串联运算符,它是流类型的特殊重载运算符,可让您将数据发送到流。它仅在您使用流时才有效。
这里你有两个选择。首先,您可以使用 std::wstring:
或者您可以使用 wstringstream(来自
标头):使用
stream.str()
获取在这种情况下得到的字符串。流方法的优点是,即使并非所有要连接的内容都已经是字符串,您也可以使用它。当然,如果您要打印到现有流(例如 wcout),则可以跳过字符串流并直接使用它。
正如其他答案所指出的,如果 SERVER_NAME 是使用 #define 创建的常量,则可以使用
L"Initial Catalog=DatabaseName;Data Source=" SERVER_NAME L";"
。但是,如果它是 const wchar_t* 则不起作用。operator<< is not a concatenation operator, it's a special overloaded operator by stream types to let you send data to stream. It only works if you're using a stream.
You have two options here. First, you can use a std::wstring:
Or you can use a wstringstream (from the
<sstream>
header):Use
stream.str()
to get the resulting string in that case. The stream approach has the advantage that you can use it even if not all the things you want to concatenate are already strings.If you're printing to an existing stream (like wcout), you can just skip the stringstream and use that directly, of course.
As other answers have pointed out, you can use
L"Initial Catalog=DatabaseName;Data Source=" SERVER_NAME L";"
if SERVER_NAME is a constant create with #define. If it is aconst wchar_t*
that won't work however.<<
和>>
不是连接运算符,而是按位移位运算符,这是完全不相关的。这对于初学者来说很困惑,因为它们已经被重载为
cout
和cin
来表示完全不同的东西。C 和 C++ 中字符串文字的串联不需要特殊运算符,因此只需键入:
<<
and>>
are not concatenation operators, but rather bitwise shifting operators, something that is totally unrelated.It's confusing for beginners because they have been overloaded for
cout
andcin
to mean something completely different.Concatenation of string literals in C and C++ is done without a special operator, so just type:
SERVER_NAME
可能不是宽字符串。但是,绝对有问题的是您的";"
不是宽字符串。尝试使用L";"
It may be that
SERVER_NAME
is not a wide-character string. However, what's definately broken is that your";"
is not a wide-character string. Try usingL";"
如果你想连接这个字符串使用 std::stringstream
If you want to concatenate this string use std::stringstream
确保
SERVER_NAME
定义为宽字符串,如下所示:或者,
Make sure
SERVER_NAME
is defined as wide-character string, something like this:Or,