簡體   English   中英

將基類的對象傳遞給派生類的引用函數

[英]Passing object of base class to function of reference to derived class

我正在嘗試編寫可以找到許多不同類型形狀之間距離的代碼。 我已經定義了一個帶有virtual distance(Shape& otherShape)函數的基類Shape來查找到另一個形狀的距離,然后想為我的所有派生類定義它。

問題是有很多可能的形狀對,所以我的解決方案是在類(圓-圓、圓-正方形、正方形-三等)之外定義一組距離函數,然后從距離函數。 我在下面添加了一個小例子來說明我的意思,只有一個派生類Circle來演示這個問題。

當我嘗試調用特定的circleCircleDistance函數時,出現錯誤,因為它無法將基類轉換為派生類。 有什么辦法可以解決這個問題,或者我的設計就不能正常工作?

enum ShapeType{CIRCLE, SQUARE};

class Shape {
public:
    ShapeType type;
    virtual double distance(Shape& otherShape) = 0;
};

class Circle : public Shape {
public:
    ShapeType type = CIRCLE;
    double distance(Shape& otherShape) override;
};


double circleCircleDistance(Circle& circle1, Circle& cirlce2){
    return 0; //pretend this does the calculation
};

double Circle::distance(Shape &otherShape) {
    switch (otherShape.type){
        case CIRCLE:
            //Here I get the error
            //cannot bind base class object of type Shape to derived class reference Circle& for 2nd argument
            return circleCircleDistance(*this, otherShape);
            
    }
}

您必須將Shape&轉換為Circle&

return circleCircleDistance(*this, static_cast<Circle&>(otherShape));

順便說一句,我會以不同的方式處理您的類型

class Shape {
public:
    virtual ShapeType get_type() const = 0;  // derived classes must override this
    virtual double distance(Shape& otherShape) = 0;
};

class Circle : public Shape {
public:
    ShapeType get_type() const override { return CIRCLE; } // here's your override
    double distance(Shape& otherShape) override;
};

...
{
   switch (otherShape.get_type()){

否則,您將遇到type從派生類/基類中隱藏的情況,具體取決於您訪問它的方式。

C++ 本身不支持多分派。 由於虛擬方法,我們只有一個分派。

所以你可以為你的案例實現雙重調度

一個(C++17)“替代”選項是使用std::variant ,它具有實現多重分派的std::visit

您可以保留繼承權或放棄繼承權。

struct Circle {
    Point center;
    float radius;
};

struct Rectangle {
    Point topLeft;
    Point bottomRight
};

using Shape = std::variant<Square, Rectangle>;

double distance(const Square&, const Square&);
double distance(const Square&, const Rectangle&);
double distance(const Rectangle&, const Square&);
double distance(const Rectangle&, const Rectangle&);

double distance(const Shape& shape1, const Shape& shape2)
{
    return std::visit([](const auto& shape1, const auto& shape2){
                           return distance(shape1, shape2);
                      },
                      shape1,
                      shape2);
}

在 c++20 中,您可以將模板特化與此類問題的概念結合使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM