use*_*198 0 c++ string const char
我试图实现下面的函数,但foo()的输出是一堆废话.我试图运行调试器,并没有在append函数中看到任何问题.但是foo()中的总变量未正确赋值"abcdef".有什么想法吗?
int main()
{
cout<<"foo is"<<endl;
foo();
return 0;
}
const char* append(const char* s1, const char* s2) {
string s(s1);
s += s2;
return s.c_str();
}
void foo() {
const char* total = append("abc", "def");
cout<<total;
}
Run Code Online (Sandbox Code Playgroud)
因为在append(),你回来了s.c_str(); 然后,s被破坏,这意味着返回的指针立即失效.
让我们append()回来std::string解决这个问题.
std::string append(const char* s1, const char* s2) {
return std::string(s1).append(s2);
}
void foo() {
std::string total = append("abc", "def");
cout << total;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
443 次 |
| 最近记录: |