如果我不使用然后删除基类 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 .
我是一名优秀的程序员,十分优秀!