将当前对象传递到方法,参考或指针
Passing current object to a method, reference or pointer
我有一个包含 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 ¬e);
您可以看到我使用的是参考,因为此方法很常被调用,我负担不起复制对象。所以我的问题是:有什么想法我如何完成此操作?或者也许将我的模型更改为可以有效的东西?
编辑
我忘了提到我也尝试过使用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 ¬e);
};
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 ¬e)=0;
//this will force all derived classes to implement it
但是,如果您不需要它,则必须在基类中实现虚拟功能:
virtual float getSample(Note ¬e){}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- 类的方法和对象。参考?智能指针?简单的初始化?
- C 将方法和字段带入外部范围,而无需明确的参考
- 为什么未调用具有常量参考返回值的超载方法
- 是否有一种方法可以始终通过值(制作副本)而不是在使用类成员函数时通过参考来传递
- std ::函数方法参考无法将dword投入到dword64
- 是否有一种方法可以避免在RVALUE和LVALUE参考中创建功能时避免重复的代码
- 通过方法返回的重新选择参考
- C++方法需要参考,无法让Cython提供
- 分配从方法返回到变量的参考
- 返回JSONDOC作为方法的参考
- 我如何验证2种模拟方法以相同的参考调用
- 传递向量作为参考的正确方法是什么
- 更改对未弃用方法C 的参考
- 正确的方法返回getter中的字符串参考
- STD :: Atomic Load方法与STD :: shared_ptr一起使用时会减少参考计数
- 将当前对象传递到方法,参考或指针
- 有什么方法可以将指针指向参考