首页 > 解决方案 > 获取指向继承类的基类指针以使用基类函数

问题描述

我在使用基本的多态性功能时遇到了问题。我有一个带有绘图函数的基类和两个派生类,每个派生类也实现了一个绘图函数。我想使用一个指向派生类的基类指针,来使用基类的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。先感谢您。

标签: c++inheritancepolymorphism

解决方案


推荐阅读