与调用"(矩形)(双精度、双精度)"不匹配

no match for call to `(rectangle) (double, double)'

本文关键字:双精度 不匹配 矩形 调用      更新时间:2023-10-16

下面是我的代码:

class rectangle
{
    double length,width;
public:
    rectangle()
    {
        length=0;
        width=0;
    }
    rectangle(double len,double wid)
    {
        length=len;
        width=wid;
    }
    double display()
    {
        return(length*width);
    }
    rectangle operator+(rectangle& rect)
    {
        rectangle recta;
        recta.length=this->length+rect.length;
        recta.width=this->width+rect.width;
        return rectangle(length,width);
    }
};
int main()
{
    rectangle rect1,rect2,rect3;
    rect1(7.0,8.9);
    rect2(11.4,12.8);
    rect3=rect1+rect2;
    cout<<rect1.display()<<endl;
    cout<<rect2.display()<<endl;
    cout<<rect3.display()<<endl;
    getch();
    return 0;
}

当你像这样声明对象时,你应该调用构造函数:

rectangle rect1(7.0, 8.9);

否则,您实际上不是调用构造函数,而是调用操作符(),而您没有在类的某个地方定义该操作符,从而导致错误。


同样,+操作符的重载是不正确的,因为您返回的是this: return rectangle(length,width);,而实际上您应该返回recta,因为这是您应用操作符的对象。

把它们放在一起,你的程序应该是这样的:
#include <iostream>
using namespace std;
class rectangle
{
    double length,width;
public:
    rectangle()
    {
        length=0;
        width=0;
    }
    rectangle(double len,double wid)
    {
        length=len;
        width=wid;
    }
    double display()
    {
        return(length*width);
    }
    rectangle operator+(const rectangle& rect) const
    {
        rectangle recta;
        recta.length=this->length+rect.length;
        recta.width=this->width+rect.width;
        return recta;
    }
};
int main()
{
    rectangle rect1(7.0, 8.9), rect2(11.4,12.8), rect3;
    rect3=rect1+rect2;
    cout<<rect1.display()<<endl;
    cout<<rect2.display()<<endl;
    cout<<rect3.display()<<endl;
    return 0;
}

rect1(7.0, 8.9);试图找到operator()(double, double)的过载,而您还没有实现。

你是指rectangle rect1(7.0, 8.9);等吗?这就是如何调用构造函数

一行:

rect1(7.0,8.9);

在你的矩形对象上调用operator(),但是你没有定义这个操作符,这就是为什么你得到这个错误。我认为你想做的是调用构造函数,当你实例化对象时必须这样做,像这样:

rectangle rect1(7.0, 8.9);

这里至少有一个问题:

rectangle rect1,rect2,rect3;
rect1(7.0,8.9);
rect2(11.4,12.8);

必须在定义对象的位置提供构造参数。否则,编译器会认为你在调用一个函数。

rectangle rect1(7.0,8.9);
rectangle rect2(11.4,12.8);
rectangle rect3;

您定义了一个构造函数,但试图使用调用重载。

构造函数,即与结构/类具有相同名称的方法,仅在初始构建时使用,通常在初始声明点。你写:

         rectangle rect1,rect2,rect3; 
         rect1(7.0,8.9); 
         rect2(11.4,12.8); 

第一行调用默认构造函数,然后构建矩形。接下来的几行尝试将它们作为函数调用——因为它们已经创建了,所以不再尝试构造。(具体来说,它现在正在尝试调用operator()(double,double))。

要解决这个问题,您应该在声明点初始化/构造它们:

rectangle rect1(7.0, 8.9);
rectangle rect2(11.4, 12.8);
rectangle rect3 = rect1 + rect2;

rect1(7.0,8.9);

不调用rectangle构造函数。它像调用函数一样调用rect1;从技术上讲,它正在调用rectangle::operator()。因为rectangle没有这样的操作符,所以会出现编译错误。

如果要调用构造函数,正确的语法是

rectangle rect1(7.0, 8.9);