与调用"(矩形)(双精度、双精度)"不匹配
no match for call to `(rectangle) (double, double)'
下面是我的代码:
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);
- 为什么我的数组双精度函数不起作用?
- 使用 int32_t 而不是双精度运行矢量点积是否更快?
- f 是指向函数的指针,该函数采用 int,并返回指向不带任何内容并返回双精度的函数的指针
- 为什么我的比较运算符不比较我的点长和双精度值?
- 为什么输出是整数而不是双精度?
- Fmod 函数清楚地输出一个预期的双精度值,但 if(fmod == 预期的双精度值)的计算结果不是 true
- C++ 警告:在一个声明中将截断从双精度初始化为浮点数,但在另一个声明中则不初始化
- "+=" 操作在类型之间不起作用 std::复杂<double>和__complex__双精度
- 当两个相等的双精度的相对比较不起作用时,我该怎么办?
- 为什么双精度引用值在分配给C++中的浮点变量时不会更改
- atof() 返回浮点数而不是双精度
- CIN 双精度和不带空格的字符串会导致错误
- 为什么当我使用双精度时,Qt<->Matlab 正确写入和读取我的字节,但存储 uint32 的字节不正确?
- 为什么双精度不存储两个整数的乘积
- C++ 将 int 转换为双精度不起作用
- C++ 双精度不起作用
- 双精度不能正确减去小数
- 与调用"(矩形)(双精度、双精度)"不匹配
- 运算符不匹配>>操作数类型为 IFstream 和双精度
- 为什么从浮点返回方法返回双精度不会在 c++ 中导致任何错误/警告