#include<iostream>
using namespace std;
const float PI = 3.141593;
class Point
{
public:
Point(int xx = 0, int yy = 0) {
x = xx;
y = yy;
}
Point(Point &p);
int getX() {
return x;
}
int getY() {
return y;
}
~Point() {}
private:
int x, y;
};
class Circle :public Point {
public:
friend Circle operator+(const Circle& circle1,const Circle& circle2);
Circle(float r);
Circle();
float area();
//float operator+(Circle &c2) const;
~Circle() {}
private:
float radius;
};
Point::Point(Point &p) {
x = p.x;
y = p.y;
}
Circle::Circle(float r) {
radius = r;
}
Circle::Circle() {
}
float Circle::area() {
return PI * radius * radius;
}
/*float Circle::operator + (Circle &circle2) const {
return(PI * circle2.radius *circle2.radius + PI * radius * radius);
}*/
int main() {
float sum;
Point b(4, 5);
cout << b.getX() << endl << b.getY() << endl;
float radius;
cout << "Enter the radius of Circle:";
Circle circle1(3);
float area1 = circle1.area();
Circle circle2(4);
float area2 = circle2.area();
cout << "Circle1 area is" << area1 << endl;
cout << "Circle2 area is" << area2 << endl;
cout << "sum of area1 and area2 is\n" << area1 + area2 << endl;
sum = circle1+circle2;
float area;
//area = circle1 + circle2;
cout << "area = " << area << endl;
return 0;
}
Circle operator+(const Circle& circle1,const Circle& circle2)
{
return(circle1.radius * circle1.radius*PI+PI * circle2.radius * circle2.radius);
}
/*
/*float Circle::operator + (Circle &circle2) const {
return(PI * circle2.radius *circle2.radius + PI * radius * radius);
}*/用这种方式float area;
//area = circle1 + circle2;可以返回float的area
而现在没被注释掉的部分用friend Circle operator+(const Circle& circle1,const Circle& circle2);编译出现错误,
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 C2440 “=”: 无法从“Circle”转换为“float” Project7 该如何更改
很明显你这个友元函数的返回实际值类型和声明的返回值类型不搭配,而且无法完成隐式转换,所以才会报错。
看你意图你想怎么用法:
如果想得到数值类型,那么返回值类型改成float没毛病,就是楼上的解决办法;
如果你想得到是Circle类,那么你要把返回语句修改一下,可以修改成如下
1 Circle operator+(const Circle& circle1,const Circle& circle2) 2 { 3 return{(circle1.radius )* (circle1.radius)*PI+PI * (circle2.radius) * (circle2.radius)}; 4 } 5 6 //以上是利用列表初始化的方法 7 //或者 8 Circle operator+(const Circle& circle1,const Circle& circle2) 9 { 10 return Circle{(circle1.radius )* (circle1.radius)*PI+PI * (circle2.radius) * (circle2.radius)}; 11 } 12 //{}和()在这里等价,理论上都是利用你自己声明的Circle(float)转换构造函数实现的。
把+号重载的定义和声名返回值改成float就可以了。。。