我可以有一个函数/方法传递一个参数通过引用和一个重载传递它的值在C + +? [英] Can I have a function/method passing an argument by reference and an overload passing it by value in C++?

查看:127
本文介绍了我可以有一个函数/方法传递一个参数通过引用和一个重载传递它的值在C + +?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,这当然是可能的,因为这个可编译的例子可以显示:

  static void Teste(int x){} 
static void Teste(ref int x){}
static void Teste()
{
int i = 0;
Teste(i);
Teste(ref i);
}



但是可以用C ++ / CLI)与构造函数?见下面的例子:

  class Foo 
{
Foo(int bar)
{
//初始化Foo实例...
}
Foo(int& bar)
{
//初始化Foo b $ b}

// ...
}

虽然这个类使用这些构造函数编译,我不能看到如何选择何时我应用一个是另一个,也就是调用是ambiguos,因为没有关键字我知道这个目的在C#中的ref。我在一个构造函数中尝试过,其中名称必须与类相同(当然,我可以添加一个无用的参数,但我想知道是否可以)。



BTW,我googled只有像通过ref和value之间有什么区别?但没有覆盖这样的重载。我想,作为解决方法,我可以使用指针,感谢取地址(& );或者如上所述具有额外的无用参数。



提前感谢,

我想知道的是,

您可以在C ++中完成类似的操作。 >  struct Foo 
{
Foo(int / * bar * /){}
Foo(int& / * bar * /){}
};


int main()
{
int value = 5;
Foo foo(static_cast< const int&>(value));

return 0;
}

强制转换为 const 将导致重载解析忽略构造函数接受一个非常量引用,并将通过值。


In C# this is certainly possible, as this compilable example can show:

static void Teste(int x) { }
static void Teste(ref int x) { }
static void Teste()
{
    int i = 0;
    Teste(i);
    Teste(ref i);
}


But can it be done in C++(/CLI) with a constructor? See the example below:

class Foo
{
    Foo(int bar)
    {
        // initializing "Foo" instance...
    }
    Foo(int &bar)
    {
        // initializing "Foo" instance...
    }

    //...
}

Although this class does compile with these constructors I can't see how to choose when I apply one are the other, that is, the call is ambiguos, as there is no keyword I know for this purpose as "ref" in C#. I tried it in a constructor, where the name must be the same as the class (of course I can add a useless parameter, but I want to know if I can not do it).

BTW, I googled and only got things like "what's the difference between passing by ref and by value?" but nothing covering overloading like this. And I guess that as workarounds I can use pointer, thanks to the "take the address of" (&); or have, as mentioned above, an extra useless parameter. But what I want to know is: can I have overloads like these (by ref/by value)?

Thanks in advance,

解决方案

You can accomplish something similar in C++ by providing an explicit cast to the desired type.

struct Foo
{
    Foo(int /*bar*/) {}
    Foo(int &/*bar*/) {}
};


int main()
{
    int value = 5;
    Foo foo(static_cast<const int&>(value));

    return 0;
}

The cast to const will cause overload resolution to ignore the constructor taking a non-const reference and will settle on passing by value.

这篇关于我可以有一个函数/方法传递一个参数通过引用和一个重载传递它的值在C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆