gpt4 book ai didi

c++ - 尝试为 C 字符串创建文本行类

转载 作者:太空狗 更新时间:2023-10-29 20:55:02 27 4
gpt4 key购买 nike

我是 C++ 的新手,在执行我的第一个程序时遇到了一些麻烦。我需要创建一个 Line 类,它只包含一个 char (c-string) 数组以及一个长度和一个最大容量。 linePtr 成员变量的类型为 char*。这是我所拥有的:

行.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

行.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;
}

主要.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 字段被写入时,我收到消息:“读取字符串字符时出错”。我确定我在做一些愚蠢的事情,但我想不通。

最佳答案

您没有在第二个构造函数中以 null 终止字符数组。在方法末尾添加这一行:

linePtr[1] = '\0';

关于c++ - 尝试为 C 字符串创建文本行类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244670/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com