在另一个方法中调用依赖于对象的方法

C++: Calling object dependent methods within another method

本文关键字:方法 对象 依赖于 另一个 调用      更新时间:2023-10-16

我正在努力将一些处理从c++驱动程序移动到我工作环境中的类中的新方法。我已经开始研究这个方法,但是当我试图从新编写的方法调用类中存在的其他依赖对象的方法时,我遇到了问题。下面是一些代码:

bool resample_edf(VVectorDouble& sigin_a, VVectorDouble& sig_out_a,
                  long out_freq_a) {
  // display debugging information
  //
  if (debug_level_d >= Edf::LEVEL_DETAILED) {
    fprintf(stdout, "Edf::resample_edf(): starting resample/n");
  }
  // get the labels in the file
  //
  char* labels[Edf::MAX_NCHANS];
  long num_channels = Edf::get_labels(labels);
  long num_samples = (long) Edf::get_duration() * Edf::get_sample_frequency();
...

get_labels(labels), get_duration()get_sample_frequency()方法都是我正在使用的Edf类的方法,但是当我试图编译它时,我得到了这个错误。

edf_01.cc:2240:45: error: cannot call member function ‘long int Edf::get_labels(char**)’ without object
   long num_channels = Edf::get_labels(labels);
                                             ^
edf_01.cc:2242:47: error: cannot call member function ‘double Edf::get_duration()’ without object
   long num_samples = (long) Edf::get_duration() * Edf::get_sample_frequency();

所有的方法都是公共方法,但是它们使用的一些变量在类中是受保护的。

我不确定如何解决这个问题,但我会继续调查。谢谢你的帮助。如果需要更多的信息,请告诉我。 编辑:我想可能有一些误解,所以我会提供更多的信息。

调用该方法的实用程序中已经存在一个Edf对象。这个实用程序现在看起来是这样的:

// local include files
//
#include <Edf.h>
...
int main(int argc, const char** argv) {
...
  // create an Edf object
  //
  Edf edf(Edf::LEVEL_NONE);
  // resample the signal
  //
  if (!edf.resample_edf(sig_in, sig_out, out_freq)) {
    fprintf(stdout, " **> nedc_resample_edf: error resampling signaln");
    return((status = -1))
  }
...

resample_edf方法是edf对象中的一个方法。在那个方法中,我希望能够从对象中调用其他方法,但这样做会出现错误。在此方法中重新实例化edf对象对我没有帮助。我已经尝试了多种方法,但都不起作用。

我最初没有包括实用程序的运行方式,因为类的编译与实用程序无关。问题来自于该方法如何调用来自同一对象的其他方法。Edf类非常大,因此很难向您提供全部内容。

如果原文不够清楚,请原谅

您说您正在将代码移动到类中的新方法中,但该方法是自由的(它不属于Edf类)。使用以下命令使其属于Edf类:

bool Edf::resample_edf(VVectorDouble& sigin_a, VVectorDouble& sig_out_a,
                  long out_freq_a)

并确保将此函数原型添加到您的问题中未显示但假定存在的class Edf {...}定义中。

之类的
class Edf
{
//...
bool resample_edf(VVectorDouble& sigin_a, VVectorDouble& sig_out_a,
                      long out_freq_a);
//...
};

你可以从你的函数定义中删除所有的Edf::

我还注意到您在fprintf

中使用/n而不是n

您还没有向我们展示Edf类/结构体,但是错误消息非常清楚。

error: cannot call member function ... without object

Edf类/结构中调用static函数时,Edf::get_labels(labels);的用法是正确的。

但是,对于非静态成员函数,您需要类/结构的对象实例。

例如:

Edf edf; // Of course I don't actually know if this class is default constructible
edf.get_labels(labels);

虽然类似上面的代码示例将解决编译错误,但它不太可能真正解决您的问题(即,默认构造的对象实例可能无法获得您试图检索的标签)。

也许Edf类的实例需要作为参数传递给resample_edf函数?


从你的评论听起来resample_edfEdf的成员函数。

bool resample_edf(VVectorDouble& sigin_a, VVectorDouble& sig_out_a,
                  long out_freq_a)
{
    // ...
    // Just call your other member functions directly since `this` is an instance
    // of the `Edf` object
    get_labels(labels);
    // ...
}