我对C++很陌生,在实现我的第一个程序时遇到了一些问题。我需要创建一个Line类,它只包含一个数组char
(c-string)以及长度和最大容量。 linePtr
成员变量的类型为char*
。以下是我有:试图为c字符串创建一个文本行类
Line.h:
#pragma once
#ifndef LINE_H
#define LINE_H
#include <iostream>
using namespace std;
class Line {
private:
char* linePtr{nullptr};
int lineLength;
int lineCapacity;
public:
Line(); //default ctor
Line(char);
~Line();
friend ostream& operator<<(ostream& output, const Line& l);
};
#endif // !LINE_H
Line.cpp:
#include <iostream>
#include <cstring>
#include "Line.h"
using std::cout;
using std::endl;
using std::strcpy;
using std::strlen;
const int LINE_CAPACITY = 5000; //arbitrarily set
Line::Line() {
cout << "Default ctor" << endl;
linePtr = new char[1]{ '\0' };
lineCapacity = LINE_CAPACITY;
lineLength = 0;
}
Line::Line(char cstr) {
cout << "ctor Line(char cstr)" << endl;
linePtr = new char[2];
lineCapacity = LINE_CAPACITY;
lineLength = 1;
linePtr[0] = cstr;
}
ostream& operator<<(ostream& out, const Line& l) {
return out << l.linePtr;
}
Main.cpp的:
#include <iostream>
#include "Line.h"
using namespace::std;
int main() {
Line l1;
cout << l1 << endl;
Line l2('x');
cout << l2 << endl;
system("pause");
return 0;
}
当我与调试运行时,它被写入的linePtr
字段我收到消息:“读取字符串的字符时出错”。我确信我在做一些愚蠢的事情,但我无法弄清楚。
您是否有'Line.h'向我们展示? –
答案已经给出了解决方案。但顺便说一句,我认为LineCapacity应该保存分配的字节数。否则它是无用的。 – Christophe
为什么不使用'std :: string'并从所有头痛中拯救自己?使用'char *',试着复制'Line'对象,你会发现你仍然有麻烦。 – PaulMcKenzie