簡體   English   中英

如何擁有抽象數據類型的參數?

[英]How to have a parameter of an abstract data type?

我有一個名為shape的抽象類。

class Shape{
public:
    virtual const ColorRGB getColor() const;
    virtual double rayIntersectionDistance(Ray r) = 0;
};

現在我從Shape派生了以下類。

  1. class Sphere: public Shape { //implementation goes here }
  2. class Plane: public Shape { //implementation goes here }

我已經在這兩個類中實現了getColor()rayIntersectionDistance(Ray r)方法,以及特定於這些類的其他方法。

所以現在,在另一個名為Scene 的類中,我有一個render()方法,它的原型是:

void render(int width, int height, Shape s);

這似乎不起作用,編譯器抱怨我說:

錯誤:無法將參數“s”聲明為抽象類型“Shape”

我怎樣才能做到這一點? 實現這一目標的更好方法是什么?

按值傳遞Shape意味着傳遞Shape的實例。 但是Shape是抽象的,因此無法創建實例。

改為傳遞指針或引用。 如果您不打算修改傳遞的對象,則const限定(這也將阻止傳遞聲明為const的對象,因為它們不應更改)。

 void func(Shape &s);    // define these functions as required
 void func2(Shape *s);
 void func3(const Shape &s);

 int main()
 {
        Sphere s;   // assumed non-abstract

        const Sphere s2;

        func(s);     // will work
        func2(&s);    // ditto

        func3(s);   // okay
        func3(s2);  // okay

        func(s);   // rejected, as s2 is const
 }

編輯:

正如 Barry 在評論中提到的,也可以傳遞智能指針,例如std::unique_pointer<Shape>std::shared_pointer<Shape> - 並且可以按值傳遞。 正如 Richard Hodges 所提到的,這在實踐中是不尋常的,盡管這是可能的。 事實上,任何管理指針或Shape引用的類型都可以傳遞——假設它的構造函數(特別是復制構造函數)實現了適當的行為。

暫無
暫無

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

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