调用类中的方法
Call a method in a class
>我有一段代码定义了一类 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();
}
在这里,我们使用您提到的构造函数创建一个名为 A
的Matrix2x2
对象,并在 A
(即我们刚刚创建的Matrix2x2
的实例)上调用 CalcDeterminant
。如果 CalcDeterminant
是 static
方法并采用类型 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();
相关文章:
- 如何强制从重写方法调用重写的方法基方法?
- C++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用