2014-04-10 52 views
0

我有幾類:虛擬方法調用<<

class Shape{ 
/* ... */ 
public: 
    virtual double field() = 0; 
    virtual double circumference() = 0; 
}; 

class Circle: public Shape{ 
protected: 
    Point center; 
    double R; 
public: 
    Shape(Point &p1, double R){ 
     this->center=p1; 
     this->R = R; 
    } 
    double field(){ 
     return M_PI *this->R * this->R; 
    } 
    double circumference(){ 
     return 2* M_PI * this->R; 
    } 
    friend ostream & operator<<(ostream &ostr, const Circle &f); 
}; 

的朋友重載運算符是:

ostream & operator<<(ostream &ostr, const Circle &f){ 
    ostr<<"Radius: "<<f.R<<endl; 
    ostr<<"Circumference: "<<f.circumference()<<endl; 
    ostr<<"Field: "<<f.field()<<endl; 
    return ostr; 
} 

和主代碼包含:

/* ... */ 
Point p = {0,0}; 
Circle c = Circle(p, 10); 
cout<<c; 

該錯誤在內部加載operator<<

過客「常量圈」爲「本」的「虛擬雙圓)::場(」的說法

但是,當我改變double field(){double field() const{我得到:

無法分配的抽象類型對象'Circle'

我想我不完全理解virtual的用法。有人可以解釋我做錯了什麼嗎?

+1

使基礎和(!)派生虛擬函數const –

+0

如果您使用C++ 11,「override」關鍵字將阻止您遇到這些情況。在應該覆蓋虛擬方法的每個方法頭的末尾使用它。然後編譯器會檢查它是否實際覆蓋,如果不是,則拋出一個錯誤。 –

回答

1

圈,只要你改變它的功能領域()爲const變成抽象的,因爲field() const實際上比field()一個完全不同的方法,這就是爲什麼field()然後保持未定義在Circle所以它是抽象的。

我建議您使用Circle::field()中的新C++ 11-ish關鍵字override與編譯器通信,您確實打算重寫虛擬方法。如果繼承類型中的field函數不存在和/或與基類中的任何虛擬方法兼容,則編譯器拒絕編譯。

+1

@Michał看看http://stackoverflow.com/questions/3982496/const-keyword-appended-to-the-end-of-a-function-definition-what-does-it-do, –

相關問題