2014-04-10 53 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, –

相关问题