gpt4 book ai didi

C++ 帮助连接 TCHAR

转载 作者:行者123 更新时间:2023-11-28 05:53:26 29 4
gpt4 key购买 nike

我最近了解到可以在代码开头定义的 ## 功能。我正在尝试编译以下代码:

#include <windows.h>
#include <tchar.h>
#include <iostream>
#include <stdio.h>
#include <string>

#define paste(x,y) *x##*y

int main()
{

TCHAR *pcCommPort = "COM";
TCHAR *num = "5";

cout << paste(pcCommPort,num);
return 0;
}

我不断收到以下错误:

expression must have arithmetic or unscoped enum type

我不喜欢我在“定义粘贴”行中使用指针这一事实。没有任何指针,它只会返回变量“pcCommPort5”。我想要的是“COM5”。

我已经尝试过 _tcscat、strcat、strcat_s,visual studio 不喜欢其中任何一个....

最佳答案

## 不会连接任意的东西(尤其不是字符串)。它的作用是将解析器中的符号合并为一个符号。

让我们删除其中一个 * 看看发生了什么:

#include <iostream>

#define TO_STRING_HELPER(x) #x
#define TO_STRING(x) TO_STRING_HELPER(x)
#define CONCAT(x, y) *x##y

int main() {
char *pcCommPort = "COM";
char *num = "5";
std::cout << TO_STRING(CONCAT(pcCommPort, num)) << std::endl;
}

Output :

*pcCommPortnum

CONCAT 在此代码中的作用是:

  1. x展开为pcCommPort,将y展开为num。这给出了表达式 *pcCommPort##num
  2. 将两个符号 pcCommPortnum 连接成一个新符号:pcCommPortnum。现在表达式是 *pcCommPortnum(记住,最后一部分 (pcCommPortnum) 都是一个符号)。
  3. * 后跟符号 pcCommPortnum 的形式完成对完整宏的评估。这成为表达式 *pcCommPortnum。请记住,这是两个不同的符号:*pcCommPortnum。这两个符号只是一个接一个。

如果我们尝试使用*x##*y,编译器会做的是:

  1. x展开为pcCommPort,将y展开为num。这为我们提供了表达式 *pcCommPort##*num
  2. 将两个符号 pcCommPort* 连接成一个新符号:pcCommPort*
  3. 此处,预处理器遇到错误:单个符号 pcCommPort* 不是有效的预处理标记。请记住,此时它不是两个单独的符号(不是两个符号 pcCommPort 后跟 *)。它是一个单个符号(我们称之为 token )。

如果你想连接两个字符串,最好使用 std::string .你不能*用预处理器做你想做的事。

*不过请注意,编译器会将连续的字符串文字合并在一起(即 "COM""5" 将合并为一个字符串 "COM5" 由编译器)。但这仅适用于字符串文字,因此您必须 #define pcCommPort "COM"#define num "5",此时您可以执行 pcCommPort num(没有任何进一步的宏),编译器会将其计算为字符串 "COM5"。但除非您真的知道自己在做什么,否则您真的应该只使用 std::string

关于C++ 帮助连接 TCHAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34713506/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com