我有幾類:虛擬方法調用<<
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
的用法。有人可以解釋我做錯了什麼嗎?
使基礎和(!)派生虛擬函數const –
如果您使用C++ 11,「override」關鍵字將阻止您遇到這些情況。在應該覆蓋虛擬方法的每個方法頭的末尾使用它。然後編譯器會檢查它是否實際覆蓋,如果不是,則拋出一個錯誤。 –