我已尝试过所有内容,但代码无效,我无法理解原因。
我有两节课。 这是基类:
class Vegetables
{
private:
char *nameStr;
char *countrySrc;
int seasonRd;
public:
Vegetables()
{
cout << "Default constructor for Vegetables" << endl;
nameStr = new char[20];
nameStr = "Unknown";
countrySrc = new char[20];
countrySrc = "Unknown";
seasonRd = -1;
}
virtual ~Vegetables()
{
delete[]nameStr; //Here happens the error (_crtisvalidheappointer(block))
delete[]countrySrc;
cout << "Destructor for Vegetables" << endl;
}
};
它继承了类'Inherited Unit':
class InhUnit : public Vegetables
{
private:
Delivery delivery_;
Vegetables vegetables;
int quantity;
int price;
int delivPrice;
public:
InhUnit() :Vegetables(),delivery_(OwnCosts), vegetables(), quantity(-1), price(-1), delivPrice(-1)
{
cout << "Default constructor for Inherited Unit" << endl;
}
~InhUnit()
{
cout << "Destructor for Inherited Unit" << endl;
}
};
弹出此错误的原因可能是什么?
答案 0 :(得分:5)
这不是你复制字符串的方式,而是使用strcpy
Vegetables()
{
cout << "Default constructor for Vegetables" << endl;
nameStr = new char[20];
strcpy(nameStr, "Unknown");
countrySrc = new char[20];
strcpy(countrySrc, "Unknown");
seasonRd = -1;
}
您正在做的是分配一些内存并将其分配给指针。然后在下一行中,您指定指向字符串的指针,而不是将字符串复制到您已分配的内存中。
当你调用delete[]
因为指针没有指向你分配的内存时,你得到了一个错误。
答案 1 :(得分:0)
你应该使用像std :: string这样的字符串类来避免这种指针问题。
答案 2 :(得分:0)
更正代码
class Vegetables {
private:
std::string nameStr; // Use std::string instead of C-style string
std::string countrySrc;
int seasonRd;
public:
// Use constructor initialization list
Vegetables() : nameStr("Unknown"), countrySrc("Unknown"), seasonRd(-1) {
cout << "Default constructor for Vegetables" << endl;
}
virtual ~Vegetables() {
cout << "Destructor for Vegetables" << endl;
}
};