2015-05-23 42 views
1

在我的代碼,我調用這樣的功能:錯誤:左值要求爲一元「和」操作數

Simulator::Schedule (Seconds(seconds), 
        &HelloProtocol::sendScheduledInterest(seconds), this, seconds); 

這裏是上述函數的簽名:

/** 
    * @param time the relative expiration time of the event. 
    * @param mem_ptr member method pointer to invoke 
    * @param obj the object on which to invoke the member method 
    * @param a1 the first argument to pass to the invoked method 
    * @returns an id for the scheduled event. 
    */ 
    template <typename MEM, typename OBJ, typename T1> 
    static EventId Schedule (Time const &time, MEM mem_ptr, OBJ obj, T1 a1); 

而功能sendScheduledInterest的定義()是:

void 
HelloProtocol::sendScheduledInterest(uint32_t seconds) 
{ 
    //... 
} 

我收到以下編譯錯誤:

hello-protocol.cpp: In member function ‘void ns3::nlsr::HelloProtocol::scheduleInterest(uint32_t)’: 
hello-protocol.cpp:58:60: error: lvalue required as unary ‘&’ operand 

如果我在函數調用之前刪除&,它提供了以下錯誤,而不是:

hello-protocol.cpp: In member function ‘void ns3::nlsr::HelloProtocol::scheduleInterest(uint32_t)’: 
hello-protocol.cpp:58:75: error: invalid use of void expression 
+2

'HelloProtocol'被定義爲'Void',但是你正在嘗試把它的地址。 –

+0

當我刪除操作員的地址時,會給出不同的錯誤。這是爲什麼? – AnilJ

+0

刪除'&',然後將'void'作爲參數傳遞給函數,這沒有任何意義。它本質上是一樣的錯誤,但編譯器在過程的另一個點上發現它。 –

回答

2

您正在取回返回值sendScheduledInterest的地址而不是方法本身的地址。刪除(seconds)位。

好像你可能打算在seconds值到該呼叫綁定到sendScheduledInterest

有了這個可以這樣實現標準庫:

變化Schedule

EventId Schedule(const Time&, std::function<void()>); 

然後用它作爲

Schedule(Seconds(seconds), bind(&HelloProtocol::sendScheduledInterest, this, seconds)); 
+0

日程安排功能來自另一個庫,我無法更改它。 – AnilJ

5

HelloProtocol::sendScheduledInterestvoid功能。這意味着它返回沒有值。你既不能在void函數的返回值上調用操作符的地址(&),也不能將它作爲參數傳遞給另一個函數,除非該類型也是void,只有在涉及到一些模板時纔會發生。

看來確實要函數指針傳遞作爲這樣的說法:

Simulator::Schedule(
    Seconds(seconds), 
    &HelloProtocol::sendScheduledInterest, 
    this, 
    seconds); 

在這兩種情況下,編譯告訴你的問題是什麼。

在第一種情況下,void表達式是而不是左值。您可以將左值視爲可在賦值語句左側分配的值。運營商的地址(&)只能應用於左值。

在第二種情況下,您嘗試在不允許的情況下使用void表達式,即作爲其形式參數類型爲非void的函數的參數。

相關問題