【发布时间】:2013-07-22 16:20:52
【问题描述】:
目前正在学习 c++,也许是因为我现在真的很沮丧,但我真的无法用我的小脑袋来解决这个问题:
有一个类构造函数:
Class (const char* file);
我在主课中这样使用它:
char* chararr = new char[2048];
//stuff with charrarr
// std::cout << chararr would be: "C:\stuff\paths\etc\"
Class c( strcat(chararr , "filename.file"));
//I want it to be: "C:\stuff\paths\etc\filename.file
Class c2( strcat(chararr , "filename2.file2"));
////I want this to be: "C:\stuff\paths\etc\filename2.file2" but it is instead
// "C:\stuff\paths\etc\filename.filefilename2.file"
问题是 strcat 修改了 chararr 所以我第二次这样做时,使用 Class c2,一切都搞砸了......我猜这是一个非常非常基本的事情,它让我更加沮丧知道我错过了一些非常明显的东西......
【问题讨论】:
-
你知道你可以简单地说
Class c("filename.file");吗? -
你需要一个复制构造函数来深度复制
char * -
你也在 strcating 一个未初始化的数组 - 看看这个 - stackoverflow.com/questions/8311942/…
-
如果您使用的是 MS Visual C++,请单击函数名称(例如 strcat)并按 F1 获取帮助,包括相关函数。如果您使用的是 Linux,cplusplus.com、linux.die.net/man 等
-
如果您正在编写 Class,请考虑修改它以接受 std::string 而不是 const char*,以避免自己管理内存。