2012-11-02 51 views
0

我有一個Track類,其中包含一個包含Note對象的多圖構件。一個的Note類的方法是這樣的:將當前對象傳遞給方法,參考或指針

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

Note還具有Generator類型的成員,我需要調用類,它需要一個Note作爲參數的getSample方法。我需要通過當前的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); 

}; 

回答

1

您必須聲明你的Generator類作爲抽象的,試試這個宣言:

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

但是,如果你不需要它,你必須在基類反正實現虛擬功能:

virtual float getSample(Note &note){} 
2

this在C指針++,所以你你要用

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

我也試過,但它不工作,更新我的文章。 – networkprofile

+0

@Sled這是一個完全不同的問題。你爲什麼沒有發佈錯誤信息開始?你爲什麼不張貼真實的代碼?無論如何 - http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-doi-i-fix處理這些錯誤。 –

+0

我以爲使用'getSample(* this);'也是錯誤的(因爲它不工作),所以我只是第一個出錯的方式。真正的代碼是什麼意思? – networkprofile

4

this是一個指針,你的代碼需要一個參考。試試這個

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

我也嘗試過,但它不起作用,更新了我的帖子。 – networkprofile

+1

那麼錯誤意味着它說什麼,你沒有定義你聲明的虛擬方法之一。無論是或者你正在錯誤地構建你的代碼。在任何情況下,*這是正確的,另一個問題是另一個問題。 – john

+1

剛剛注意到丹尼斯埃爾莫林的回答。他可能是對的,你需要一個純粹的虛擬方法。 'getSample方法在子類中實現'不夠好。 – john

1

傳遞引用,而不是指向getSample()的指針。這就是寫這種方式:

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

我也試過,但它不起作用,更新了我的帖子。 – networkprofile