gpt4 book ai didi

c++ - 错误 : lvalue required as unary ‘&’ operand

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:59 25 4
gpt4 key购买 nike

在我的代码中,我这样调用函数:

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

最佳答案

HelloProtocol::sendScheduledInterest 是一个 void 函数。这意味着它返回无值。您既不能在 void 函数的返回值上调用运算符 (&) 的地址,也不能将其作为参数传递给另一个函数,除非该类型也是 void,这只有在涉及某些模板时才会发生。

看来您实际上打算像这样将函数指针作为参数传递:

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

在这两种情况下,编译器都会准确地告诉您问题所在。

在第一种情况下,void 表达式不是左值。您可以将左值视为可以分配给赋值语句左侧的东西。运算符 (&) 的地址只能应用于左值。

在第二种情况下,您试图在不允许的地方使用 void 表达式,即作为形式参数类型为非 void 的函数的参数。

关于c++ - 错误 : lvalue required as unary ‘&’ operand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com