c++ - 获取指向继承类的基类指针以使用基类函数
问题描述
我在使用基本的多态性功能时遇到了问题。我有一个带有绘图函数的基类和两个派生类,每个派生类也实现了一个绘图函数。我想使用一个指向派生类的基类指针,来使用基类的draw函数实现。然后我想使用派生类的draw函数。
#include <iostream>
#include <string>
#include <fstream>
#ifndef SHAPEHEADER_H
#define SHAPEHEADER_H
using namespace std;
class Shape {
public:
Shape(float, float);
virtual ~Shape() = default;
virtual float draw() const { return 94.9; };
private:
float a;
float b;
};
#endif // !SHAPEHEADER_H
#include <iostream>
#include <string>
#include <fstream>
#include "ShapeHeader.h"
#ifndef CIRCLEHEADER_H
#define CIRCLEHEADER_H
using namespace std;
class Circle : public Shape{
public:
Circle(float);
float draw() const override { return pi * radius*radius; };
private:
float radius;
static float pi;
};
#endif // !SHAPEHEADER_H
Shape s0(1.0, 1.0);
Circle c0(1.0);
Square sq0(3.0, 4.0);
Shape *shape0 = &s0;
Shape *shape1 = &c0;
Circle *circle0 = &c0;
cout << "Shape:" << shape0->draw() << endl;
cout << "Circle:" << circle0->draw() << endl;
system("PAUSE");
cout << "Pointing to circle and square with shape pointer" << endl;
cout << "Circle:" << shape1->draw() << endl;
system("PAUSE");
这不会产生形状绘制输出,它会输出圆形绘制功能。
在 Tutorialspoint.com 上,他们有以下代码:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
为什么当他们使用指向继承类的基类指针并调用draw时,所有三个姿势,他们的程序都会输出基类函数。在我的代码中,我有相同的设置,一个指向继承类对象的基类指针,它会输出继承的类draw。先感谢您。
解决方案
推荐阅读
- kubernetes - 无法从 istio 连接到 kafa 集群
- jmeter - 如果 jmeter 中的 HTTP 请求,则在请求 URL 和正文中传递自动增量变量
- ember.js - 这个值在哪里定义 - “(action (mut foo) true)”?
- authentication - 如何使用 django-axes 禁止客户端 IP 地址,而不是发送登录请求的角度服务器的本地 IP 地址?
- python - 十六进制字符串操作以提取计数器?
- sql - 实体管理器 createNativeQuery:可能容易受到 SQL/JPQL 的攻击
- javascript - 自定义滚动动画 - 暂停部分和水平滚动元素
- python - 是否可以从父类调用子类的函数?
- java - 在 IntelliJ 中等效于 Java 的 Visual Studio Post 构建脚本
- python - 如何修复“ImportError:没有名为 pssevrsn 的模块”