不会显示所需输出的虚拟继承
Virtual Inheritance that wont show desired output
我得到了一个名为 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,则该函数将按预期工作。
相关文章:
- 大小虚拟继承中的派生类
- C++ 多级虚拟继承编译问题
- 如何正确获得虚拟继承?
- 避免C++虚拟继承
- 虚拟继承基构造函数消除
- 虚拟继承中是否存在多重继承?
- 了解虚拟继承类 vtables 和 vptr 创建
- 当键是虚拟继承中涉及的基类指针时,对 std::unordered_map 项的访问崩溃
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- C++ 不明确访问 - 虚拟继承
- 虚拟继承中来自基数的虚拟调用
- 虚拟继承:调用没有匹配函数
- 虚拟继承的内部机制
- 联合虚拟继承
- C++虚拟继承类的大小
- C++虚拟继承、虚拟析构函数和 dynamic_cast<void*>
- 虚拟继承构造函数的组装
- 虚拟继承情况下类的意外大小
- 虚拟继承情况下的 vtable
- C++解决没有虚拟继承的钻石继承问题