获取定义为父类的子类以输出子函数
Getting the a child class defined as the parent class to output the child function
我有一个定义如下的类:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Shape {
protected:
float width, height;
public:
virtual ~Shape(){}
void set_data (float a, float b){
width = a;
height = b;
}
virtual string getType() {
return "Shapes";
}
};
class Polygon: public Shape {
public:
virtual ~Polygon(){};
virtual string getType() {
return "Polygon";
}
};
class Triangle: public Polygon {
public:
virtual ~Triangle(){};
virtual string getType() {
return "Triangle";
}
};
我想得到一个使用这个类的程序
int main () {
Shape poly = Polygon();
Shape tri = Triangle();
std::cout << poly.getType() << std::endl;
std::cout << tri.getType() << std::endl;
return 0;
}
例如,有没有办法让poly.getType()
打印出Polygon
?现在它正在打印出Shapes
.我知道我是否做到了
Polygon poly = Polygon()
这就可以了,但我想将poly
存储为 Shape
对象,使用 Polygon
构造函数构造它,并确保
poly.getType()
返回Polygon
,而不是Shapes
。
多态性仅适用于非值类型;即引用和指针。而且由于引用必须立即绑定,因此在这里没有多大用处。
最好的办法是使用 std::unique_ptr<Shape> poly(new Polygon());
并使用
poly->getType();
我正在使用std::unique_ptr
,所以我不需要显式调用delete
。 std::shared_ptr
也可以工作,但请查阅文档,以便使用最适合您的用例的文档。
顺便说一下,在子类中重写函数时,您无需重复virtual
。您只需在基类中标记函数virtual
。
您的代码受到对象切片的影响。用:
int main () {
std::unique_ptr<Shape> poly = new Polygon();
std::unique_ptr<Shape> tri = new Triangle();
std::cout << poly->getType() << std::endl;
std::cout << tri->getType() << std::endl;
return 0;
}
创建一个变量字符串类型。在每个可实例化的子类中设置它。在 Shape 中有一个函数 getType 来返回它。
上面的答案基本上是正确的:"我需要使用指针"是关键。
这解决了我的问题:
int main ()
{
Polygon poly = Polygon();
Shape* testing = &poly;
std::cout << testing->getType() << std::endl;
return 0;
}
我将在大约一个小时内接受您的答案,因为堆栈溢出让我在接受之前等待一段时间。谢谢
相关文章:
- 从 c 或 cpp 系列子函数返回到主函数
- C++:为什么我的掷骰子函数在掷骰子数量时只返回偶数整数?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 我想要一个具有子函数的函数访问相同的命名函数,而不使用它取决于其子类的类
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- C++调用子函数
- 如何在C++从父实例调用子函数
- 我将 c++ 矢量数据集转换为 c 数组.我将相同的数据集传递到一个应该给出相同输出的函数中
- 是否有理由大多数/所有 try-catch 示例只对 throw 语句使用 void 子函数
- CRTP 在父级析构函数中调用子函数
- 在函数和子函数中调用相同的关键部分
- 整数模板参数和子函数调用
- 如何在C++中创建具有子函数的对象
- 使用子函数的继承函数
- 从void子函数检索int值到C++中的函数
- 现有的标准函子/函数,用于检查等于 0
- 通过指针修改子函数中函数的局部变量的内容
- 重载算子函数==
- 如何编写返回类型的函数,该类型是其子函数的返回类型
- 获取定义为父类的子类以输出子函数