簡體   English   中英

C ++中虛函數和/或const的“丟棄限定符”錯誤

[英]“Discards qualifiers” error with virtual function and/or const in c++

我對這個問題的研究越深入,似乎就越困惑。 這是一個家庭作業問題,涉及到增加我們教授給我們提供的代碼。 我知道問題與const關鍵字有關,還有一些非常令人困惑的新應用程序。

有一個通用類Object,從中繼承了幾個子類(Sphere,Cone,Polygon)。 以下是Object中的類:

public: // computational members                                                
    // return t for closest intersection with ray                               
    virtual float intersect(const Ray &ray) const = 0;

    // return color for intersection at t along ray r                           
    virtual const Vec3 appearance(const World &w,
                                  const Ray &r, float t) const = 0;

    //The following function is added by me
    virtual const Vec3 normal(Vec3 p);
};

我添加了最后一個功能,正常。

因此,例如在Sphere類中,就這樣實現了:

const Vec3 Sphere::normal(Vec3 p)
{
  return (p - d_center).normalize();
}

當我“ make”時,出現以下錯誤:

Appearance.cpp: In member function ‘const Vec3 Appearance::eval(const World&, const Vec3&, const Vec3&, Vec3, int) const’:
Appearance.cpp:46: error: passing ‘const Object’ as ‘this’ argument of ‘virtual const Vec3 Object::normal(Vec3)’ discards qualifiers
make: *** [Appearance.o] Error 1

您能幫我理解為什么會這樣嗎? 謝謝你的幫助。

當錯誤消息引用方法的'this' argument ,表示您正在調用該方法的對象(指向)。 例如,在shape->normal(v)shapethis參數。

要指定給定方法不會修改其自己的對象( this參數),您需要在其聲明后附加 const 因此,更改此:

virtual const Vec3 normal(Vec3 p);

對此:

virtual const Vec3 normal(Vec3 p) const;

表示在const對象上調用normal(...)是“安全的”。

同樣,更改此:

const Vec3 Sphere::normal(Vec3 p)

對此:

const Vec3 Sphere::normal(Vec3 p) const

就像編譯器所說的那樣,嘗試從const函數中調用非const函數將失去對象本身的恆定性。

您還必須將normal函數設為const,否則請避免調用它。

暫無
暫無

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

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