gpt4 book ai didi

c++ - operator<< 内部的虚方法调用

转载 作者:行者123 更新时间:2023-11-28 06:57:25 27 4
gpt4 key购买 nike

我有几门课:

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<< :

passing 'const Circle' as 'this' argument of 'virtual double Circle::field()'

但是当我改变double field(){double field() const{我得到:

Cannot allocate an object of abstract type 'Circle'

我想我不完全理解 virtual 的用法.有人可以解释我做错了什么吗?

最佳答案

一旦你将它的函数 field() 更改为 const,Circle 就会变得抽象,因为 field() const 实际上是一个与 field() 完全不同的方法,后者这就是为什么 field() 然后在 Circle 中保持未定义,所以它是抽象的。

我建议您在 Circle::field() 中使用新的 C++11-ish 关键字 override 与您实际打算覆盖的编译器进行通信一个虚方法。如果继承类型中的 field 函数不存在和/或不兼容基类中的任何虚方法,则编译器将拒绝编译。

关于c++ - operator<< 内部的虚方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22982210/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com