私はC++を初めて使用しています。私は最初のプログラムを実装するのに少し問題があります。私はchar
(c-string)の配列だけでなく、長さと最大容量を含むLineクラスを作成する必要があります。 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