c++ - 如何修复类函数 "prototype does not match"和 "cadidate is"错误

标签 c++ class

我正拼命地尝试完成这最后一项任务,但我完全不知道这些错误试图告诉我做什么。错误是这样的:

“‘double Rectangle::calculateArea()’的原型(prototype)与‘Rectangle’类中的任何原型(prototype)都不匹配”(第 40 行)

“候选人是:int Rectangle::calculateArea()”(第 11 行)

“‘double Rectangle::calculatePerimeter()’的原型(prototype)与‘Rectangle’类中的任何原型(prototype)都不匹配”(第 45 行)

“候选人是:int Rectangle::calculatePerimeter()”(第 12 行)

这是我在这个论坛上的第一篇帖子,所以我提前为它的格式错误道歉

我没有尝试任何东西,因为我在论坛上找到的解决方案都没有直接与我的问题相关(或者我认为如此)。

谢谢

// Rectangle.cpp
using namespace std;
class Rectangle
{
public: 
  void setLength(double length);
  void setWidth(double width);
  double getLength();
  double getWidth();

  int calculateArea() {return width*length;}
  int calculatePerimeter() {return (width*2) + (length*2);}


private:    
  double length;
  double width;
}; 

void Rectangle::setLength(double len)
{
  len = length;
}

void Rectangle::setWidth(double wid)
{
  wid = width;
}

double Rectangle::getLength()
{
  return length;
}

double Rectangle::getWidth()
{
  return width;
}

double Rectangle::calculateArea()
{
  return (width*length)
}

double Rectangle::calculatePerimeter()
{
  return ((width*2) + (length*2))
}

最佳答案

您已经使用错误的返回类型(int 而不是 double)在类定义中定义了函数

class Rectangle
{
  //...
  int calculateArea() {return width*length;}
  int calculatePerimeter() {return (width*2) + (length*2);}
  //..
}; 

然后你在类外重新定义它们

double Rectangle::calculateArea()
{
  return (width*length)
}

double Rectangle::calculatePerimeter()
{
  return ((width*2) + (length*2))
}

而且这些函数定义不正确

void Rectangle::setLength(double len)
{
  len = length;
  ^^^^^^^^^^^^
}

void Rectangle::setWidth(double wid)
{
  wid = width;
  ^^^^^^^^^^^
}

它们必须像这样定义

void Rectangle::setLength(double len)
{
  length = len;
}

void Rectangle::setWidth(double wid)
{
  width = wid;
}

所有这些功能

  double getLength();
  double getWidth();

  int calculateArea() {return width*length;}
  int calculatePerimeter() {return (width*2) + (length*2);}

应该用限定符 const 声明

  double getLength() const;
  double getWidth() const;

  double calculateArea() const {return width*length;}
  ^^^^^^
  double calculatePerimeter() const {return (width*2) + (length*2);}
  ^^^^^^

关于c++ - 如何修复类函数 "prototype does not match"和 "cadidate is"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57330186/

相关文章:

c++ - Sleep(x) 导致计算机进入休眠状态

c++ - PThread - 尽管调用了 pthread_join,但线程提前退出

c++ - Visual Studio 2015 缩进多行 for 语句

c++ - 是否有嵌套枚举类的接口(interface)机制?

c++ - 重载的Double Equal运算符无法正常工作

python - 在 python 中,有什么方法可以在定义类后立即自动运行函数?

c++ - 如何(可移植地)使用 C++ 类层次结构和动态链接库

c# - 如何将复杂的 XML 转换为 .NET 类?

c++ - arduino (esp8266/esp32) 股票回调类成员函数

c++ - 对 `gemmkernel_' 的 undefined reference -- 从 Fortran 调用的 C++ 例程