从具有基类函数的派生类打印
Printing from a derived class with a base class function
我正试图用派生类中函数的函数打印,其中包含基类中的函数,但我不确定是否应该如何打印出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();
}
如果您希望多态性正常工作,也可以考虑将此方法设置为const
和virtual
。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中打印目录
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 通过基类引用派生类后打印的错误值
- C++ - 打印派生类对象的矢量<base*> 元素
- C++ 打印从字符串字符派生的整数
- 在基类中打印派生类名
- 使用引用此对象的基类指针向量打印派生类对象
- 从具有基类函数的派生类打印
- C++ 指针向量<base_class*>放置派生类但切片打印
- 给定一个基类作为参数,如果传递了一个派生类的特征,如何使用 op<< 重载来打印派生类的特征?