将当前对象传递到方法,参考或指针

Passing current object to a method, reference or pointer

本文关键字:方法 参考 指针 对象      更新时间:2023-10-16

我有一个包含 Note对象的多胶合成员的Track类。Note类的方法之一是:

float Note::getValue(){
    float sample = generator->getSample(this); // not working
    return sample;
}

Note还具有Generator类型的成员,我需要调用该类的getSample方法,该方法期望Note作为参数。我需要传递当前的Note对象,并尝试使用关键字this进行操作,但这是不起作用的,并且给我带来了错误Non-const lvalue reference to type 'Note' cannot bind to a temporary of type 'Note *'

这是getSample的方法定义的样子:

virtual float getSample(Note &note);

您可以看到我使用的是参考,因为此方法很常被调用,我负担不起复制对象。所以我的问题是:有什么想法我如何完成此操作?或者也许将我的模型更改为可以有效的东西?

编辑

我忘了提到我也尝试过使用generator->getSample(*this);,但这也无法使用。我收到此错误消息:

Undefined symbols for architecture i386:
  "typeinfo for Generator", referenced from:
      typeinfo for Synth in Synth.o
  "vtable for Generator", referenced from:
      Generator::Generator(Generator const&) in InstrumentGridViewController.o
      Generator::Generator() in Synth.o
      Generator::Generator(Generator const&) in InstrumentGridViewController.o
      Generator::Generator() in Synth.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

这是我的Generator类的样子(在子类中实现了getample方法):

class Generator{
public:
    virtual float getSample(Note &note);
};

this是一个指针,您的代码为参考。尝试这个

float sample = generator->getSample(*this);

this是C 的指针,因此您需要

float sample = generator->getSample(*this);

通过参考,而不是指向getsample()的指针。那是这样写的:

float Note::getValue(){
    float sample = generator->getSample(*this);
    return sample;
}

您必须将Generator类声明为抽象,尝试以下声明:

virtual float getSample(Note &note)=0; 
//this will force all derived classes to implement it

但是,如果您不需要它,则必须在基类中实现虚拟功能:

virtual float getSample(Note &note){}