调用类中的方法

Call a method in a class

本文关键字:方法 调用      更新时间:2023-10-16

>我有一段代码定义了一类 2x2 矩阵。然后,我制作了一种方法,该方法可以通过定义以下命令来计算 2x2 矩阵的行列式:

double Matrix2x2::CalcDeterminant() const
{
return val00*val11-val10*val01; //these are the values of the matrix entries
}

现在,如果我想在我尝试编写的类的某个实例上测试它(我不确定这是否是正确的词):

int main()
{
Matrix2x2 A=Matrix2x2::Matrix2x2(1,2,3,4); // Matrix2x2 is a constructor that takes 4 real numbers as input and returns a 2x2 matrix
Matrix2x2::CalcDeterminant(A); //this is where my coding fails. What is wrong with this line?
}

但是代码在最后一行失败,这显然不是调用该方法的正确方法。我做错了什么?我对这一切很陌生。

改为:

int main() {
    Matrix2x2 A(1,2,3,4);
    double det = A.CalcDeterminant();
}

在这里,我们使用您提到的构造函数创建一个名为 AMatrix2x2对象,并在 A(即我们刚刚创建的Matrix2x2的实例)上调用 CalcDeterminant。如果 CalcDeterminantstatic 方法并采用类型 Matrix2x2 的参数,则您提供的代码将起作用。

C++中的每个成员函数都有一个特殊的参数,称为 this 。你不需要像你一样显式传递它。this参数有点像stdio.h函数的FILE *参数。它为类的此实例提供句柄。

成员函数调用遵循以下形式

inst.func(args);

所以在您的情况下,您可以致电

A.CalcDeterminant();

编写classname::func(args)的唯一时间是func是否是static成员函数。这些类型的函数没有this指针;也就是说,它们无法访问任何包含类的成员。例如

class time {
    // some private members
public:
    // other members
    static time now();
};

now函数获取当前时间。使now是静态的,因为它不使用time的任何成员。 now会这样称呼

time::now();

我推荐C++编程语言

这是

基本的C++语法:

int main() {
  Matrix2x2 A(1,2,3,4);
  A.CalcDeterminant();
}

您使用的语法适用于静态方法。您的方法不是静态的,因此您需要将该方法应用于您的对象:

A.CalcDeterminant();