在 C++ 中将 const std::string 赋值给 std::string [英] Assigning const std::string to std::string in c++
本文介绍了在 C++ 中将 const std::string 赋值给 std::string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将 const std::string 变量分配给 std::string 变量.但是遇到了一些与内存相关的错误.代码如下:
I am trying to assign a const std::string variable to std::string variable.But getting some memory related error. code is like below:
#include <iostream>
#include <string>
using namespace std;
std::string sender1;
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
}
int main()
{
fun();
cout<<sender1<<endl;
return 0;
}
推荐答案
您忘记了 fun
中的 return
.如果您像这样更改该功能:
You've forgotten a return
in fun
. If you change that function like this:
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
return sender;
}
然后代码将编译并运行良好.
then the code will compile and run fine.
这篇关于在 C++ 中将 const std::string 赋值给 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文