没有用于调用的匹配函数

no matching function for call to

本文关键字:函数 调用 用于      更新时间:2023-10-16
#include <iostream>
using namespace std;
int n;
void displaysum(double mat[n][n])
{
  double sum= 0;
  for(int j=0;j<n;j++)
    sum += mat[j][j];
  cout<<"Sum of Diagnols Elements is n"<<sum;
}
int main()
{
  cout << "what are the number of rows or column in the matrix" << endl;
  cin >> n;    
  double matrix[n][n];
  for (int row = 0; row < n; row++)
  {
    for (int column = 0; column < n; column++)
      cin >> matrix[row][column];
  }
  displaysum(matrix)
  return 0;
}

我不明白为什么我收到一个错误,因为没有匹配的函数可以调用XCODE.即使我尝试更改函数原型中的变量,它仍然会给我同样的错误。

我不明白为什么我收到一个错误,因为没有匹配的函数可以调用XCODE.

基本问题是C++希望第二维在编译时是常量,以便进行类型检查。如果你想解决这个问题,你必须使用指针(AFAIK)。您可以通过将displaysum声明更改为

void displaysum(double **mat)

并为原始函数中的matrix进行适当的分配。

如果你不喜欢这个,那么,欢迎来到C++的类型系统。在函数声明中,double mat[n][n]被视为double (*)[n]。这实际上是有道理的,但为什么它不认为matrix属于那种类型,是因为n不是恒定的。您可以更改呼叫

displaysum(matrix);

对此:

displaysum(static_cast<double (*)[n]>(matrix);

并收到奇怪的错误

static_cast from 'double (*)[n]' to 'double (*)[n]' is not allowed

(这不是你从类型系统中得到的最奇怪的错误)