简体   繁体   English

为什么我不能直接在临时对象上调用operator()?

[英]Why can't I call operator() on temporary objects directly?

What I want to do can be summarized into the following code: 我想做的事情可归纳为以下代码:

struct A{};

struct B{
    A& a;
    B(A& a) noexcept : a(a){}
    int operator()(int) {}
};

int main(){
    A a;
    B(a)(2);
}

And my compiler (g++ 6) rejected the code complaining that a shadows a parameter. 和我的编译器(g++ 6)拒绝代码抱怨a阴影的参数。 However, if I try to explicitly call operator() , it works as expected. 但是,如果我尝试显式调用operator() ,它会按预期工作。

It seems that g++ will ignore the parentheses and see the statement as a declaration. 似乎g++将忽略括号并将该语句视为声明。

Is this the specified or expected behavior? 这是指定的还是预期的行为?

This is one of those icky parsing rules which catches you every now and again. 这是那些icky解析规则之一,一次又一次地抓住你。 As you suggest, B(a)(2); 如你所知, B(a)(2); is actually equivalent to B a(2); 实际上相当于B a(2); , so your code tries to initialize a B with an int . ,所以你的代码试图用int初始化一个B

To fix this, you can use C++11's uniform initialization: 要解决此问题,您可以使用C ++ 11的统一初始化:

B{a}(2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以直接调用operator()而无需创建临时对象吗? - Can I call directly operator() without creating a temporary object? 为什么我可以在临时std :: ofstream对象上使用`operator &lt;&lt;`? - Why can I use `operator<<` on temporary std::ofstream objects? 为什么临时对象上的函数调用操作符有时会被解释为不影响参数的声明? - Why can function call operator on temporary objects sometimes be interpreted as a declaration that does not shadow a parameter? 为什么我不能打电话给operator()? - Why can't I call operator()? 为什么我不能使用“=”运算符将数组变量直接分配给另一个数组变量? - Why can't I assign an array variable directly to another array variable with the '=' operator? 我可以在gdb漂亮的打印机中直接调用程序的`operator[]`吗? - Can I call `operator[]` of the program directly in a gdb pretty printer? 不要临时调用QString :: operator []() - Don't call QString::operator[]() on temporary 为什么我不能在派生的 class 运算符&gt;&gt;中调用基本 class 运算符&gt;&gt;? - Why i can't call base class operator>> in derived class operator>>? 为什么我不能直接调用由指向成员的指针访问的实例的方法 - why can't I directly call a method of an instance which is accessed by pointer-to-member 当我按值而不是按引用返回时,为什么不能调用运算符? - Why can't I call on the operator when I return by value instead of by reference?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM