我有一段代码定义了一类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?
}
但代码在最后一行失败,这显然不是调用该方法的正确方法。我究竟做错了什么?我对这一切都很陌生。
答案 0 :(得分:1)
更改为:
int main() {
Matrix2x2 A(1,2,3,4);
double det = A.CalcDeterminant();
}
在这里,我们使用您提到的构造函数创建一个名为Matrix2x2
的{{1}}对象,并在A
上调用CalcDeterminant
(即我们A
的实例刚刚创建)。如果Matrix2x2
是CalcDeterminant
方法并采用static
类型的参数,则您提供的代码将起作用。
答案 1 :(得分:1)
C ++中的每个成员函数都有一个特殊的参数,称为this
。你不需要像你那样明确地传递它。 this
参数有点像FILE *
函数的stdio.h
参数。它提供了此类实例的句柄。
成员函数调用遵循
形式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 ++编程语言。
答案 2 :(得分:0)
这是基本的C ++语法:
int main() {
Matrix2x2 A(1,2,3,4);
A.CalcDeterminant();
}
答案 3 :(得分:0)
您使用的语法是静态方法。您的方法不是静态的,因此您需要将th方法应用于您的对象:
A.CalcDeterminant();