gpt4 book ai didi

c++ - 是否可以在 C++ 中增加变量范围?

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:20 24 4
gpt4 key购买 nike

我对作用域在 C++ 中的作用方式感到有点困惑。现在看来,在我的 else 语句中,我的 finalStr 被创建,然后在它离开范围后立即销毁。

std::string finalStr;
char curLine[128];
if( BINARY_ASCII == 1 ) //ignore this case please :D
{
cdata = convertBSTRToByteArray(data , numChars);
}
else
{
bstrInputString = ( LPCWSTR ) data;

std::strcpy(curLine, bstrInputString.operator char *());
std::string finalStr(curLine);

cout << "data is: " << finalStr.data() << "\n"; //prints the right string
}

cout << "string is: " << finalStr.data() << "\n"; //prints nothing except "string is: "

我该如何解决这个问题?我相信我需要 else 语句中的复制构造函数来复制我的字符数组。有没有解决的办法?感谢阅读..

最佳答案

finalStr 声明了两次,一次在 if-else 语句外,一次在 if-else 语句内。在内部作用域中声明的变量将隐藏在外部作用域中的变量,因此您拥有的是一个局部变量,它将在封闭大括号的末尾被销毁。

但是,std::string 可以很容易地分配给,所以只需使用它:

finalStr = curLine;

关于c++ - 是否可以在 C++ 中增加变量范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454222/

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