gpt4 book ai didi

c++ - 为什么此删除会导致核心转储?

转载 作者:太空宇宙 更新时间:2023-11-04 16:16:49 25 4
gpt4 key购买 nike

如果我不使用然后删除基类 Output 的指针,此代码将正常工作。 Output 的析构函数被调用并且似乎正常工作。我在这里遗漏了什么吗?

// multiple inheritance
// Testing overload of muliple inheritance of pure virtual functions.

#include <iostream>
#include <string>

using namespace std;

class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
~Polygon() = default;
virtual int area() = 0;
};

class Output {
private:
string* myString;

public:
Output() {
myString = nullptr;
}

Output(const string& s) {
myString = new string(s);
}

// This seems to work, but ther core dump happens right afterwards.
~Output() {
cout << "delete called with: " << myString << '\n';
if (myString != nullptr)
delete myString;
}
virtual int area() = 0;
void print () {
cout << *myString << this->area() << '\n';
}
};



class Rectangle: public Polygon, public Output {
public:
Rectangle (int a, int b) : Polygon(a,b), Output{"A Rectangle's area is: "} {}
int area () {
return width*height;
}
};

class Triangle: public Polygon, public Output {
public:
Triangle (int a, int b) : Polygon{a,b}, Output{"A Triangle's area is: "} {}
int area ()
{ return width*height/2; }
};

int main () {
Output * ptr1 = new Rectangle(4,5);
Output * ptr2 = new Triangle(4,5);

ptr1->print();
ptr2->print();

// Causes core dump.
delete ptr1;
delete ptr2;

return 0;
}

最佳答案

这段代码有几个主要问题:

首先,你不应该为此使用多重继承。这是完全没有必要的,并且会导致很难追踪错误。

其次,您不需要在删除指针之前测试 nullptr - 这是多余的,因为 delete 已经这样做了。

第三,你的基类都没有虚析构函数。 (你当前的错误)

第四,你违反了Rule of 3在您的 Output 类中(并且可能需要在所有类中使用它)。

第五,假设string表示std::string。没有理由让它成为 string* - 只需使用 std::string 并避免分配和释放它。

我没有解决您的设计问题,但您的内存访问和多态问题已解决here .

#include <iostream>
#include <string>

using namespace std;

class Polygon
{
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual ~Polygon() { } // needed!
virtual int area() = 0;
};

class Output
{
private:
std::string myString; // no need to be a pointer

public:
Output() { }

Output(const string& s) : myString(s) { }

virtual ~Output() { } // also needed!
virtual int area() = 0;
void print () {
cout << myString << this->area() << '\n';
}
};



class Rectangle: public Polygon, public Output
{
public:
Rectangle (int a, int b) : Polygon(a,b), Output{"A Rectangle's area is: "} {}
int area () {
return width*height;
}
};

class Triangle: public Polygon, public Output
{
public:
Triangle (int a, int b) : Polygon{a,b}, Output{"A Triangle's area is: "} {}
int area ()
{ return width*height/2; }
};

int main ()
{
Output * ptr1 = new Rectangle(4,5);
Output * ptr2 = new Triangle(4,5);

ptr1->print();
ptr2->print();

// Causes core dump.
delete ptr1;
delete ptr2;

return 0;
}

编辑:可以找到实现所需程序的更好方法的示例 here .

关于c++ - 为什么此删除会导致核心转储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com