从具有基类函数的派生类打印

Printing from a derived class with a base class function

本文关键字:派生 打印 类函数 基类      更新时间:2023-10-16

我正试图用派生类中函数的函数打印,其中包含基类中的函数,但我不确定是否应该如何打印出Shape to String函数和Rectangle to String函数中的信息。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Shape
{
public:
    Shape(double w, double h);
    string toString();
private:
    double width;
    double height;
};
Shape::Shape(double w, double h)
{
    width = w;
    height = h;
}
string Shape::toString()
{
    stringstream ss;
    ss << "Width: " << width << endl;
    ss << "Height: " << height << endl;
    return ss.str();
}
class Rectangle : public Shape
{
public:
    Rectangle(double w, double h, int s);
string toString();
private:
    int sides;
};

string Rectangle::toString()
{
    //
    // Implement the Rectangle toString function
    // using the Shape toString function
    Shape::toString();
    cout << toString();
    stringstream ss;
    ss << "Sides: " << sides << endl;
    return ss.str();
}
// Use the constructor you created
// for the previous problem here
Rectangle::Rectangle(double w, double h, int s)
    :Shape(w, h)
{
    sides = s;
}

问题中唯一可以处理的部分是注释

之后的部分

我认为问题出在这行:

cout << toString();

因为它将递归地调用自己,最终您将耗尽堆栈并得到运行时错误。

您的实现应该是:

string Rectangle::toString()
{
    // Implement the Rectangle toString function
    // using the Shape toString function
    stringstream ss;
    ss << Shape::toString();
    ss << "Sides: " << sides << endl;
    return ss.str();
}

如果您希望多态性正常工作,也可以考虑将此方法设置为constvirtual