开发者

Why won't gcc compile a class declaration as a reference argument?

开发者 https://www.devze.com 2022-12-25 08:07 出处:网络
This compiles fine in Visual studio,but why not in XCode? class A() {}; someMethod(A& a); someMethod(A()); //error: no matching function call in XCode only :(

This compiles fine in Visual studio, but why not in XCode?

class A()
{};

someMethod(A& a);

someMethod(A()); //error: no matching function call in XCode only :(  

Is this bad form? it seems annoying to have to write the following every time:

A a;
someMethod(a);  //successful compile on Xcode

Am i missing something? I am not very experienced so thank you for any hel开发者_如何学Gop!


You cannot bind a temporary to a non-const reference. It would work if you changed the function to take a const reference:

someMethod(const A& a);

In addition,

A a();

does not declare a local variable. It declares a function named a that takes no parameters and returns an object of type A. You mean:

A a;


For passing references to rvalues (of which the reference is implicitly obtained) like it's done in someMethod(A()), you need constant references. The valid declaration (including correct syntax) therefore is

void someMethod(const A& a);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号