我是c ++的新手,我在实施第一个程序时遇到了一些麻烦。我需要创建一个Line类,它只包含一个char
(c-string)数组以及一个length和max capacity。 linePtr
成员变量的类型为char*
。这就是我所拥有的:
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
字段时,我收到消息:“读取字符串字符时出错”。我确定我做的事情很愚蠢,但我无法理解。
答案 0 :(得分:4)
您不会在第二个构造函数中以null结尾字符数组。在方法的最后添加此行:
linePtr[1] = '\0';