在另一个构造函数中调用构造函数(没有要调用的匹配函数..) c++

Call constructor inside another constructor (no matching function to call...) c++

本文关键字:调用 构造函数 函数 c++ 另一个      更新时间:2023-10-16

我编写了一个数组类来创建 1d、2d 和 3d 数组,它适用于每个测试: 2d 情况数组类的构造函数示例:

Array::Array( int xSize, int ySize )
{ 
xSize_ = xSize;
ySize_ = ySize;
zSize_ = 1;
vec.resize(xSize*ySize);
}

它工作正常,但是当我需要在其他构造函数中使用此构造函数时,我得到"不匹配函数错误",我的部分代码:

class StaggeredGrid
{
public:
StaggeredGrid ( int xSize1, int ySize1, real dx, real dy ) : p_ (2,2) {}
protected:
Array p_;

完全错误:

No matching function for call to Array::Array() 
Candidates are : Array::Array(int)
Array::Array(int, int)
Array::Array(int, int, int)

如果有人知道这个问题,我将不胜感激

数组类有三个构造函数,分别采用一个、两个和三个整数。如果 StaggeringGrid 有一个默认的构造函数,它将调用 Array::Array(),它不存在,从你告诉的内容。

问题是,然后你声明并且不要在StaggeredGrid的构造函数中初始化

    Array p_;

应该调用默认构造函数,代码中似乎缺少该构造函数。

简单地添加空的默认构造函数应该可以解决问题。

    class Array
    {
    public:
        Array(){}
        // ...
    };

在类中定义任何构造函数后,编译器不会为类定义隐式默认构造函数。

在您的情况下,您已经定义了参数化构造函数"Array(int xSize, int ySize )",但您正在使用默认构造函数创建一个类,即数组p_。这将调用编译器未完全找到的默认构造函数。

溶液:

数组类中引入默认构造函数