gpt4 book ai didi

c++ - 无法从 const char* 转换为 const char *&

转载 作者:搜寻专家 更新时间:2023-10-31 00:26:56 27 4
gpt4 key购买 nike

我正在 VC++ 上编写一个简单的 UTF8 到 WideStr 函数。

MtoW.h

#pragma once
#include <Windows.h>
#include <string>
using namespace std;
wstring UTF8toWide(const char*& in);

MtoW.cpp

#include "MtoW.h"
#include <string>
#include <cassert>
using namespace std;
wstring UTF8toWide(const char*& in) {
int size = MultiByteToWideChar(CP_UTF8, 0, in, -1, NULL, 0);
wchar_t* wide_str = new wchar_t[size];
int result_size = MultiByteToWideChar(CP_UTF8, 0, in, -1, wide_str, size);
assert(size == result_size);
return wstring(wide_str);
}

主要.cpp

#include <string>
#include <iostream>
#include "MtoW.h"
using namespace std;
int main()
{
string s = "hi";
//s.c_str();
//const char* q = "abc";
//const char*& c = q;
wstring q = UTF8toWide(s.c_str()); //error
}

我遇到了 cannot convert from const char* to const char *& 错误,为什么?
s.c_str() 是一个 const char* 类型,我的代码应该可以工作。

最佳答案

什么 std::string::c_str returns 是一个右值,不能绑定(bind)到对非常量(即 const char*&)的左值引用。

如果 in 不会被修改,您可以将参数类型更改为 const char* inconst char* const & in UTF8toWide(),或者改用命名变量。

string s = "hi";
const char* c = s.c_str();
wstring q = UTF8toWide(c);

关于c++ - 无法从 const char* 转换为 const char *&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733522/

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