找不到错误

时间:2011-12-13 18:51:33

标签: visual-c++

这个程序是一场噩梦,它甚至不会在跑步时给我错误,视觉工作室告诉我什么,我需要一些帮助

#include <iostream>
using namespace std;


class Textbook
{
private:
    char *aPtr;
    char *tPtr;
    int yearPub;
    int numPages;
    char bookType;
public:
    Textbook(char *, char *, int, int, char);
    void display();
    void operator=(Textbook&);
};

 Textbook::Textbook(char*string = NULL, char*string2 = NULL, int ypub = 0, int npages = 0, char btype = 'X')
{
aPtr = new char[strlen(string) +1];
strcpy(aPtr, string);

tPtr = new char[strlen(string2) +1];
strcpy(tPtr, string2);

yearPub = ypub;
numPages = npages;
bookType = btype;
}

void Textbook::display()
{
cout << "The name of the author is: " << *aPtr << endl;
cout << "The Title of the book is: " << *tPtr << endl;
cout << "The year it was published is: " << yearPub << endl;
cout << "The number of pages is: " << numPages << endl;
cout << "The initial of the title is: " << bookType << endl;
return;
}

void Textbook::operator=(Textbook& newbook)
{
if(aPtr != NULL) //check that it exists
    delete(aPtr);// delete if neccessary
aPtr = new char[strlen(newbook.aPtr) + 1];
strcpy(aPtr, newbook.aPtr);

if(tPtr != NULL) //check that it exists
    delete(tPtr); // delete if neccessary
tPtr = new char[strlen(newbook.tPtr) + 1];
strcpy(tPtr, newbook.tPtr);

yearPub = newbook.yearPub;
numPages = newbook.numPages;
bookType = newbook.bookType;
}


void main()
{
Textbook book1("sehwag", "Programming Methods", 2009, 200, 'H');
Textbook book2("Ashwin", "Security Implementation", 2011, 437, 'P');
Textbook book3;

book1.display();
book2.display();
book3.display();

book3 = book1;
book2 = book3;

book1.display();
book2.display();
book3.display();
}

我不确定问题是否存在于默认构造函数中,但这是我能想到的唯一问题,但我根本不确定如何修复它。

2 个答案:

答案 0 :(得分:1)

变化:

cout << "The name of the author is: " << *aPtr << endl;
cout << "The Title of the book is: " << *tPtr << endl;

为:

cout << "The name of the author is: " << aPtr << endl;
cout << "The Title of the book is: " << tPtr << endl;

同样改变:

aPtr = new char[strlen(string) +1];
strcpy(aPtr, string);

为:

if (string != NULL)
{
    aPtr = new char[strlen(string) +1];
    strcpy(aPtr, string);
}
else
{
    aPtr = new char[1];
    aPtr[0] = '\0';
}

并且tptrstring2同上。

您需要进行此检查的原因是因为您将NULL作为两个字符串输入的默认值,因此当您调用不带参数的构造函数时(如book3的情况),这些字符串只是NULL指针。使用NULL指针调用strlen或strcat等函数将导致出现异常,如您所见。

理想情况下,你不应该在C ++中使用C风格的字符串 - 而是使用C ++ string - 这将有助于避免上述问题。

答案 1 :(得分:1)

问题在于构造函数中的default-parameters。 你不能用NULL指针进行那种操作。

Textbook book3;

崩溃你的程序。