【发布时间】:2015-01-13 00:42:45
【问题描述】:
我是一名 c 程序员,刚刚开始使用 c++。在 c 中,如果我们从函数返回地址,那么我们传递的地址将是无效的,除非我们动态分配了该内存。 但是在 C++ 中,我没有分配内存来存储字符串。 即使从函数 copy_string 返回后,字符串“a”的地址是否仍然有效。 为什么在 main 函数中它返回正确的字符串?
#include <iostream>
#include <string>
using namespace std;
class String_copy{
public:
string str1;
string str2;
string copy_string(string str);
};
string String_copy::copy_string(string str)
{
string a;
string b;
b="Hello World!";
a = str+" "+b;
return a;
}
int main(void)
{
String_copy str;
str.str1="Wooo";
str.str2 = str.copy_string(str.str1);
cout << "Final string is \"" << str.str2 << "\"" << endl;
return 0;
}
【问题讨论】:
-
string不是char *。 -
您需要复习您的
C知识。C与您在此处的代码中看到的行为相同。想象string是 C 中的一个结构,当你按值返回结构时会发生什么? -
在此处查看此 C 示例:ideone.com/VJ1sH4 您将看到结构被复制,与被复制的字符串对象没有什么不同。不同之处在于,C++ 允许您通过使该函数可用(通过复制构造函数和赋值操作)来“微调”复制的制作方式。
-
感谢 Paul 的解释。我假设字符串在 c++ 中被视为 char * ,但它只是一个值而不是指针。 :D
标签: c++ compilation