c++ - 没有调用 ‘myclass::myclass()’ 的匹配函数

标签 c++

我正在编写一个简单的程序来计算面积,我得到的错误是:

no matching function for call to 'myclass::myclass()'

我无法理解此错误的原因以及如何解决它。

#include <iostream>
using namespace std;

class myclass{
    int length;
    int breadth;
public:
    myclass(int x, int y);
    int area(int x, int y);
};

myclass::myclass(int x,int y ){
    length=x;
    breadth=y;
}

int myclass::area(int x, int y){
    return x*y;
}

int main()
{
    myclass a;
    a.area(3,4);
}

最佳答案

在此声明中

myclass a;

应该调用类的默认构造函数,但你没有定义默认构造函数。

此外,成员函数area没有多大意义,因为它不计算类对象的面积。

有效的代码可能如下所示

#include <iostream>

class myclass
{
private:
   int length;
   int breadth;

public:
   myclass(int x, int y);
   int area() const;
};

myclass::myclass(int x,int y ) : length( x ), breadth( y )
{
}

int myclass::area() const
{
   return length * breadth;
}    

int main()
{
   myclass a(3,4);

   std::cout << "area = " << a.area() << std::endl;
} 

您也可以通过以下方式声明构造函数

   myclass( int x = 0, int y = 0 );

在这种情况下,它将是默认构造函数。

关于c++ - 没有调用 ‘myclass::myclass()’ 的匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25264525/

相关文章:

c++ - Tensorflow C++ 内存泄漏 - Valgrind

c++ - 如何使用 Qt 类和函数构建 XML 文件并转义所有非 Unicode 字符?

c++ - 在 C++ 中以不同方式处理多个输入命令的正确方法是什么?

c++ - 无法将字符数组转换为具有 utf-8 字符的 wstring

c++ - 将自定义 API 转换为 Ruby on Rails ActiveResource

c++ - ubuntu平台poco库链接错误

c++ - 如何从 const 方法生成非常量方法?

c++ - 在 opengl 中混合固定功能管道和可编程管道

c++ - 试图让 CUDA 7.5 与 GCC 5.x 一起工作

c++ - 仅使用加法的 pow 函数?