我有几类:虚拟方法调用<<
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”关键字将阻止您遇到这些情况。在应该覆盖虚拟方法的每个方法头的末尾使用它。然后编译器会检查它是否实际覆盖,如果不是,则抛出一个错误。 –