不会显示所需输出的虚拟继承

Virtual Inheritance that wont show desired output

本文关键字:虚拟 继承 输出 显示      更新时间:2023-10-16

我得到了一个名为 Shape.h 的头文件,我的任务是创建另外 4 个头文件,每个头文件代表形状:正方形、矩形、圆形和椭圆形。

头文件 Shape 由其他四个头文件继承,源文件应相应地提供头文件的输出。

写的代码很好,但输出不会给出预期的结果,我在这里需要帮助。

我向我的教练寻求帮助,即使他们帮助这很耗时,但这是值得的。

这里真正的交易是我调试,环顾代码并在代码上尝试了不同的东西,但我要么得到相同的不需要的结果,要么得到错误消息。

这是基本文件:

#pragma once
#include <string>
struct Color {
  uint8_t r, g, b;
  Color(uint8_t _r, uint8_t _g, uint8_t _b) : r(_r), g(_g), b(_b) {}
};
class Shape {
public:
  Shape(Color color) : m_color(color) {}
  virtual std::string toString() const {
    return "color=" + std::to_string(m_color.r) + ',' +
           std::to_string(m_color.g) + ',' + std::to_string(m_color.b) + 'n';
  }
  virtual float getArea() const = 0;
  virtual float getCircumference() const = 0;
  virtual ~Shape();
private:
  Color m_color;
};
// note: this method was moved here to satisfy the compiler's need for an
// out-of-line virtual function
Shape::~Shape() {}

这是 4 个继承头文件 (Square.h( 之一:

#include "Shape.h"
#include <string>
class Square :
    public Shape
{
public:
    Square(Color rgb, float width) :Shape(rgb), w(width) {}
    std::string toString() {
        return Shape::toString() + 'n'
            + "width=" + std::to_string(w) + 'n';
    }
    float getArea() const override{
        return w*w;
    }
    float getCircumference() const override {
        return w*4;
    }
private:
    float w;
};

这是用于测试的源文件:

#include <iostream>
#include <vector>
#include "Shape.h"
#include "Square.h"
void printAttributes(Shape &shape) {
    std::cout << shape.toString();
    ;
    std::cout << "area=" << std::to_string(shape.getArea()) << std::endl;
    std::cout << "circumference=" << std::to_string(shape.getCircumference())
        << 'n'
        << std::endl;
}
int main() {
    Color red{255, 0, 0 };
    Square square(red, 10.0);
    printAttributes(square);
    return 0;
}

F.ex. 正方形输出应如下所示:

color=255,0,0
width=10.000000
area=120.000000
circumference=44.000000

我的输出显示

color=255,0,0
area=120.000000
circumference=44.000000
class Square :
    public Shape
{
public:
    Square(Color rgb, float width) :Shape(rgb), w(width) {}
    std::string toString() const {
        return Shape::toString() + 'n'
            + "width=" + std::to_string(w) + 'n';
    }
    float getArea() const override{
        return w*w;
    }
    float getCircumference() const override {
        return w*4;
    }
private:
    float w;
};

在 toString 方法之后添加 const 关键字,然后将被覆盖您的基本 toString 函数。foo(( 和 foo(( const 与你的代码调用 Shape.toString(( 不同。在虚拟函数表中不会覆盖您的 Shape::toString 方法。

更正了我之前的回答。由于基类在函数签名中具有 const,而派生类没有,因此派生类 toString 函数实际上被视为不同的函数。如果将 const 添加到派生类或从超类中删除 const,则该函数将按预期工作。