类型为“const char [8]”和“const char*”的无效操作数为二进制“operator+”
Invalid operands of types ‘const char [8]’ and ‘const char*’ to binary ‘operator+
我正在尝试编写这样的 Fopen 语句:
FILE *fp;
fp = fopen("client." + receiver->get_identifier().c_str() + ".vol", "a+");
其中接收者->get_identifier() returns 一个字符串。但是,我收到标题中的错误。我阅读了 here 问题,但运气不佳,因为 fopen 的第一个参数是 const char*。我必须更改什么才能编译它?
receiver->get_identifier().c_str()
returns 一个 const char*
,而不是一个 std::string
,所以 operator+
不能启动(它的一个参数必须是一个 std::string
)。删除 c_str()
并在最后使用 std::string::c_str()
进行转换应该可以解决问题
fopen(("client." + receiver->get_identifier() + ".vol").c_str(), "a+");
这是因为你有一个 const char*
加上一个 std::string
,operator+
就可以了。
如果您可能想知道为什么不能为 const char*
定义 operator+
,那是因为 C++ 不允许基本类型的运算符重载;至少一个参数必须是用户定义的类型。
尝试将第一个参数更改为
(string("client.") + receiver->get_identifier() + ".vol").c_str()
这将添加 std::string
具有 C 风格字符串的对象,which can be done,并且只在末尾获取字符指针(通过 .c_str()
)。您的代码现在尝试添加 C 样式字符串,这是不可能的。
我正在尝试编写这样的 Fopen 语句:
FILE *fp;
fp = fopen("client." + receiver->get_identifier().c_str() + ".vol", "a+");
其中接收者->get_identifier() returns 一个字符串。但是,我收到标题中的错误。我阅读了 here 问题,但运气不佳,因为 fopen 的第一个参数是 const char*。我必须更改什么才能编译它?
receiver->get_identifier().c_str()
returns 一个 const char*
,而不是一个 std::string
,所以 operator+
不能启动(它的一个参数必须是一个 std::string
)。删除 c_str()
并在最后使用 std::string::c_str()
进行转换应该可以解决问题
fopen(("client." + receiver->get_identifier() + ".vol").c_str(), "a+");
这是因为你有一个 const char*
加上一个 std::string
,operator+
就可以了。
如果您可能想知道为什么不能为 const char*
定义 operator+
,那是因为 C++ 不允许基本类型的运算符重载;至少一个参数必须是用户定义的类型。
尝试将第一个参数更改为
(string("client.") + receiver->get_identifier() + ".vol").c_str()
这将添加 std::string
具有 C 风格字符串的对象,which can be done,并且只在末尾获取字符指针(通过 .c_str()
)。您的代码现在尝试添加 C 样式字符串,这是不可能的。