c++:派生类实现基类的虚成员函数,第二个派生类not

问题描述 投票:0回答:2
class Shape
{
    public:
      Shape() {};
      virtual void fun1();

};

class Rectangle : public Shape
{
public:
   Rectangle(int width) {width=width;}
   double width;
};
class Circle : public Shape
{
public:
   Circle(int radius) {radius=radius;}
   double radius;
   void fun1() {...} override;
};

//在运行时执行这段代码 std::shared_ptr ptr = std::make_shared(width);

这个 MWE 表明派生类 Rectangle 没有实现函数 fun1(),但是派生类 Circle 实现了。 实现这个的正确设计是什么?

c++ inheritance polymorphism
2个回答
0
投票
  • 第9行公共拼写错误。 - 在类 rectangle 你首先写双倍宽度; 比函数内部函数写 this.width=width; 因为两个宽度的名称会造成混淆,在半径上相似。

0
投票
class Shape
{
public:
    virtual void fun1() = 0;
};

class Rectangle : public Shape
{
public:
    Rectangle(const double width) 
        : width{width}
    {}

    void fun1() override 
    {}

private:
   double width;
};

class Circle : public Shape
{
public:
    Circle(const double radius)
        : radius{radius}
    {}

    void fun1() override 
    {}

private:
    double radius;    
};
© www.soinside.com 2019 - 2024. All rights reserved.