簡體   English   中英

將繼承的 function 更改為純虛擬

[英]Changing inherited function to be pure virtual

我想知道以下是否可能。 我希望我的派生 class dAfunc()更改為純虛擬,以便從dA派生的任何類都必須實現func()

即使ddA沒有實現func() ,也可以在 MSVC 下編譯類似於下面的代碼。

編譯器確實抱怨下面的代碼(見評論)。 所以我現在的問題變成了:這是一種符合標准的方式來實現我想要的嗎?

class A {
   public:
      virtual void func() { /* Some base implementation. */ }
}

class dA : public A {
   public:
      void func() override = 0;   // Is this valid?
}

class ddA : public dA {
}

Pure virtual function 應在父 class 中聲明。 考慮下面的代碼:'''

class Shape {
public:
    Shape(int init_x, int init_y) : x(init_x), y(init_y) {}

    virtual void scale(int s) = 0;
    virtual void print() = 0;
protected:
    int x;
    int y;
};

這些功能應該在兒童中實現:

class Rect : public Shape {
public:
    Rect(int init_x, int init_y, int w, int h);
    virtual void scale(int s) { //implementation }
    virtual void print() { //implementation }
private:
    int width;
    int height;
};

但是,您不必在子類中實現虛函數,因為它已在超級 class 中實現:

純虛擬 function 使您的 class 抽象,因此您不能使用它的實例。

暫無
暫無

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

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