将申明和定义中 ostream&operator<<(ostream&output,const circle&c)const去掉后可成功运行,为何
#include<iostream>#include<string>usingnamespacestd;classpoint{public:point(floatx=0,...
#include <iostream>
#include <string>
using namespace std;
class point
{
public:
point(float x=0,float y=0);
void set_point(float,float);
friend ostream & operator << (ostream &,const point
&);
protected:
float x;
float y;
};
point::point(float a,float b):x(a),y(b){}
ostream &
operator<<(ostream&output,const point&p)
{
cout<<"point"<<"("<<p.x<<","<<p.y<<")"<<endl;
return output;
}
void point::set_point(float a,float b)
{
x=a;
y=b;
}
class circle:public point
{
public:
circle(float x=0,float y=0,float radius=0);
void set_r(float r);
float arrer();
friend ostream&operator<<(ostream&,const circle&);
float area();
protected:
float radius;
};
circle::circle(float a,float b,float r):
point(a,b),radius(r){}
void circle::set_r(float r)
{
radius=r;
}
ostream&operator<<(ostream&output,const circle&c)//将标记处的两项去掉后可以通过,为什么
{
cout<<"circle"<<"("<<c.x<<","<<c.y<<")
r="<<c.radius<<" area="<<c.area()<<endl;
return output;
}
float circle::area()
{
return 3.14159*radius*radius;
}
int main()
{
point a(2,2);
cout<<a;
circle b(2,3,2);
cout<<b;
circle&c=b;cout<<c;
} 展开
#include <string>
using namespace std;
class point
{
public:
point(float x=0,float y=0);
void set_point(float,float);
friend ostream & operator << (ostream &,const point
&);
protected:
float x;
float y;
};
point::point(float a,float b):x(a),y(b){}
ostream &
operator<<(ostream&output,const point&p)
{
cout<<"point"<<"("<<p.x<<","<<p.y<<")"<<endl;
return output;
}
void point::set_point(float a,float b)
{
x=a;
y=b;
}
class circle:public point
{
public:
circle(float x=0,float y=0,float radius=0);
void set_r(float r);
float arrer();
friend ostream&operator<<(ostream&,const circle&);
float area();
protected:
float radius;
};
circle::circle(float a,float b,float r):
point(a,b),radius(r){}
void circle::set_r(float r)
{
radius=r;
}
ostream&operator<<(ostream&output,const circle&c)//将标记处的两项去掉后可以通过,为什么
{
cout<<"circle"<<"("<<c.x<<","<<c.y<<")
r="<<c.radius<<" area="<<c.area()<<endl;
return output;
}
float circle::area()
{
return 3.14159*radius*radius;
}
int main()
{
point a(2,2);
cout<<a;
circle b(2,3,2);
cout<<b;
circle&c=b;cout<<c;
} 展开
1个回答
展开全部
ostream&operator<<(ostream&output,const circle&c)
参数c是个const引用,也就是个常对象。
但是你在函数体中调用了area()函数,常对象只能调用常成员函数,而area并不是常成员函数,所以会编译出错。
解决办法是把area函数定义为常成员函数,需要修改两个地方:
声明处:float area()const;
定义处:
float circle::area()const
{
return 3.14159*radius*radius;
}
参数c是个const引用,也就是个常对象。
但是你在函数体中调用了area()函数,常对象只能调用常成员函数,而area并不是常成员函数,所以会编译出错。
解决办法是把area函数定义为常成员函数,需要修改两个地方:
声明处:float area()const;
定义处:
float circle::area()const
{
return 3.14159*radius*radius;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询