【发布时间】:2017-04-30 17:04:38
【问题描述】:
引用以下资源后:here 和 here。所以我可以看到正确的方法是如何做到这一点的。然后在阅读this 的帖子后,我可以看到我之前的警告是通过将char* "mystring" 的类型字符传递给函数的参数来修复的。
但是,对于几行非常直观的代码,我仍然收到错误消息(尽管我还没有接触过某种类型的 c++,因此我遇到了一些麻烦)。
TextDocument.h
#ifndef ____TextDocument__
#define ____TextDocument__
#include <stdio.h>
class TextDocument {
char *text;
char *docName;
public:
void SetText(char *otherText);
char *GetText();
void SetDocName(char *newName);
char *GetDocName();
int GetTextLength();
};
#endif /* defined(____TextDocument__) */
文本文档.cpp
#include <iostream>
#include "TextDocument.h"
#include "string.h"
using namespace std;
void TextDocument::SetText(char *otherText){
cout << otherText << endl;
if (text != 0)
delete text; //free the memory
text = new char[strlen(otherText)+1]; // +1 for the null char
strcpy(text, otherText); //text <- otherText
}
char *TextDocument::GetText(){
return text;
}
void TextDocument::SetDocName(char *name){
if (docName != 0)
delete docName;
docName = new char[strlen(name) + 1]; // +1 for the \0 terminator
strcpy(docName, name); // docName <- name
}
char *TextDocument::GetDocName(){
return docName;
}
int TextDocument::GetTextLength(){
if (text != 0) {
return strlen(text);
}
else return 0;
}
main.cpp
#include <iostream>
#include "string.h"
#include "TextDocument.h"
#include "Folder.h"
using namespace std;
int main(void){
TextDocument *sampleDoc;
sampleDoc = new TextDocument;
sampleDoc->SetText((char *)"some str"); // I have no idea why there is a linker error here.
return 0;
}
运行.sh
g++ *.cpp -o main
./main
输出:
Blakes-MacBook-Pro:data_encapsulation bmc$ sh run.sh
some str
main(848,0x7fff7f54b300) malloc: *** error for object 0x8000000000000000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
run.sh: line 2: 848 Abort trap: 6 ./main
问题 1
为什么它在未创建时不删除我的 char* 文本。
问题 2(侧边栏问题,不是我的直接问题)
放置所有这些 .h 文件的最佳位置在哪里?示例)我需要 #include <iostream> 和 using namespace std 在几个不同的 .h 或 .cpp 文件中,最好放在哪里;如果您只将它们放在 main 中,其他模块将无法看到它并产生错误。
第一次修复提交
所以在搞砸了这个东西之后,我通过更改行来消除错误
if (text != 0)
delete text; //free the memory
到
if (text)
delete text; //free the memory
我想我理解if (thestringeisntempty) delete text; 的逻辑,但为什么if(text != 0) delete text; 不能正常工作?
【问题讨论】:
-
你的问题不是使用 std::string 而是使用极不推荐的 new 和 delete。
-
你在TextDocument的构造函数中将文本设置为
NULL(或nullptr)吗?编辑:没关系,没有构造函数。 -
@The Techel,所以您只需使用
std::string数据成员,然后在其中重置其值?我正在努力学习最佳实践。 -
将
text初始化为NULL -
这段代码很痛苦。已经使用
std::string了!