And*_*yar 0 c++ oop visual-c++
我已经尝试了一切,但代码不起作用,我无法理解为什么.
我有两节课.这是基类:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
它继承了类'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;
}
};
Run Code Online (Sandbox Code Playgroud)
出现此错误的原因可能是什么?
这不是你复制字符串的方式,strcpy而是使用
Vegetables()
{
cout << "Default constructor for Vegetables" << endl;
nameStr = new char[20];
strcpy(nameStr, "Unknown");
countrySrc = new char[20];
strcpy(countrySrc, "Unknown");
seasonRd = -1;
}
Run Code Online (Sandbox Code Playgroud)
你正在做的是分配一些内存并将其分配给指针.然后在下一行中,您指定指向字符串的指针,而不是将字符串复制到您已分配的内存中.
当你调用delete[]因为指针没有指向你分配的内存时,你得到了一个错误.