【问题标题】:How to call a static function?如何调用静态函数?
【发布时间】:2011-05-31 13:52:32
【问题描述】:

我在我的班级Matrix 中定义了 2 个函数,如下所示(在 Matrix.hpp 中)

static Matrix MCopy( Matrix &a );   
static Matrix MatInvert( Matrix &x )
static double MatDet( Matrix &x ); // Matdef function

在我的 Matrix.Cpp 文件中,我将这些函数定义如下:

Matrix Matrix::MatCopy( Matrix &a )
{
Matrix P( a.getRow() , a.getCol() , Empty );
int j=0;
while( j != P.getRow() ){    
    int i=0;
    while( i != P.getCol() ){    
        P(j,i)=a(j,i);
        ++i;
    }
    ++j;
}
return P;
}

Matrix Matrix::MatInvert( Matrix &x )
{
Matrix aa = Matrix::MatCopy(x); // i got error message here
int n = aa.getCol();

Matrix ab(n,1,Empty);
Matrix ac(n,n,Empty);
Matrix ad(n,1,Empty);

if(MatLu(aa,ad)==-1){
    assert( "singular Matrix" );
    exit(1);
}
int i=0;
while( i != n ){    
    ab.fill(Zero);
    ab (i,0)=1.0;
    MatRuecksub(aa, ab,ac,ad,i);
    ++i;
}
 return ac; 
}

好的,这是我的 MatDef 函数

double Matrix::MatDet( Matrix &x )
{
double result;
     double vorz[2] = {1.0, -1.0};
int n = x.getRow();
Matrix a = Matrix::MatCopy(x);
Matrix p( n, 1, Empty);

int i = MatLu(a, p);
if(i==-1){  
    result = 0.0;
}
else {  
    result = 1.0;
    int j=0;
    while(j != n){    
        result *= a( static_cast<int>(p(j,0)) ,j);
        ++j;
    }
    result *= vorz[i%2];
}
  return result;
 }

但是当我编译这个时,我得到一个错误告诉我:

line 306:no matching function for call to ‘Matrix::Matrix[Matrix]’:
note: candidates are: Matrix::Matrix[Matrix&]
note:in static member function ‘static double Matrix ::MatDet[Matrix&]’:

由于我是 C++ 编程新手,所以我无法理解问题所在,所以请帮助我解决此错误。

我用过的地方

  Matrix aa = Matrix::MatCopy(x);

它显示与第 306 行相同的错误消息,但注释不同,所以我认为 MatDef 不是问题。 请给你的cmets来解决这个问题。谢谢!

【问题讨论】:

  • 您能否提供有关如何调用该方法的代码?我认为你很接近......
  • 您向我们展示的代码中似乎没有发生错误(消息说它在Matrix::MatDet。请发布该代码,并指出错误所在的行。
  • 问题似乎出在 MatDet 内部,它不在您的代码中。
  • 由于错误信息中至少有一个错字(现已修复),请问方括号是否也是错字?省略行号和其他信息也无济于事。

标签: c++ static-methods


【解决方案1】:

如果你有一个名为 A 的类并且它有一个静态函数 foo 你可以这样调用它

A::foo();

Reading material

【讨论】:

    【解决方案2】:

    您似乎正试图该类的静态成员函数访问该类的变量。静态成员函数不能访问类的常规变量。

    您需要检查@Woot4Moo 建议的链接:

    non-static vs. static function and variable

    【讨论】:

      猜你喜欢
      • 2011-10-04
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多