2016-05-15 56 views
3

我对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字段我收到消息:“读取字符串的字符时出错”。我确信我在做一些愚蠢的事情,但我无法弄清楚。

+0

您是否有'Line.h'向我们展示? –

+1

答案已经给出了解决方案。但顺便说一句,我认为LineCapacity应该保存分配的字节数。否则它是无用的。 – Christophe

+0

为什么不使用'std :: string'并从所有头痛中拯救自己?使用'char *',试着复制'Line'对象,你会发现你仍然有麻烦。 – PaulMcKenzie

回答

4

您不是在第二个构造函数中终止字符数组。在该方法的结尾处​​添加此行:

linePtr[1] = '\0'; 
+0

感谢您的答复,尝试过,但我仍然得到相同的错误。即使我的默认构造函数也给了我相同的错误。调试器显示甚至lineLength和lineCapacity的值都是荒谬的(-858993460) – lebman

+2

@KarlSamaha:-858993460在十六进制中是0xCCCCCCCC。 Visual Studio的CRT实现在调试版本中使用此值来指示未初始化的数据。即使在C'tor跑完之后你还能看到这些值吗? – IInspectable

+1

另外,如果编译器正在优化您的代码,您可能会在调试器中看到变量的奇怪值。调试时用/ Od关闭优化。 – kcraigie

相关问题