【问题标题】:Passing current object to a method, reference or pointer将当前对象传递给方法、引用或指针
【发布时间】:2012-11-02 13:13:49
【问题描述】:

我有一个 Track 类,它的 multimap 成员包含 Note 对象。 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 类的样子(getSample 方法在子类中实现):

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

};

【问题讨论】:

    标签: c++ reference pass-by-reference


    【解决方案1】:

    this 是一个指针,您的代码需要一个引用。试试这个

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

    【讨论】:

    • 嗯,这个错误意味着它所说的,你还没有定义你声明的虚拟方法之一。要么是这样,要么你正在错误地构建你的代码。无论如何*this是正确的,另一个问题是另一个问题。
    • 刚刚注意到 Denis Ermolin 的回答。他可能是对的,你需要一个纯虚拟方法。 'getSample 方法在子类中实现' 不够好。
    【解决方案2】:

    this 是 C++ 中的一个指针,所以你需要

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

    【讨论】:

    • @Sled 这是一个完全不同的问题。你为什么不发布错误消息开始?你为什么不发布真正的代码?无论如何 - stackoverflow.com/questions/12573816/… 处理这些错误。
    • 我认为使用getSample(*this); 是一样的错误(因为它也不起作用)所以我只是第一种方法我得到错误。真正的代码是什么意思?
    • @Sled 这意味着您说您尝试使用*this,但在问题中您使用this
    • 是的,我已经尝试了两种方法,但都没有工作,所以我只发布了没有* 的尝试(因为我认为两者都是错误的,因为它们都没有工作)。很抱歉造成混乱
    【解决方案3】:

    传递引用,而不是指向 getSample() 的指针。也就是这样写:

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

    【讨论】:

      【解决方案4】:

      您必须将Generator 类声明为抽象类,试试这个声明:

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

      但如果你不需要它,你必须在基类中实现虚函数:

      virtual float getSample(Note &note){}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        相关资源
        最近更新 更多