C++/CLI: Is overloading on return type only possib

2019-05-31 09:07发布

If I understand well, in C#, it is possible to do

public class X : ICloneable
{
    public X Clone() { ... }
    object ICloneable.Clone() { return Clone(); } // This calls the above
}

according to this thread. This kind of overloading is forbidden in C++, since it only depends on the return type.

Now, I would like to do this exact thing with ICloneable in C++/CLI. Is there a way ?

3条回答
Juvenile、少年°
2楼-- · 2019-05-31 09:10

This type of overloading is allowed in C# not because of different return type, but because of explicit implementation of interface - ICloneable.Clone.

About C++/CLI look here: http://msdn.microsoft.com/en-us/library/ms235235%28VS.80%29.aspx

查看更多
女痞
3楼-- · 2019-05-31 09:23

In C++ you can just leave out the second line, C++ allows covariance in overrides. Since X Clone() is compatible with the contract for object ICloneable::Clone(), it can put it directly into the v-table without needing a forwarding function.

查看更多
别忘想泡老子
4楼-- · 2019-05-31 09:32

I finally found a way:

public ref class X : public ICloneable
{
    virtual System::Object^ Clone2() sealed = ICloneable::Clone;
public:
    X(X const&); // Traditional C++ copy constructor
    X^ Clone();
};

System::Object^ X::Clone2() { return this->Clone(); }
X^ X::Clone() { return gcnew X(*this); }
查看更多
登录 后发表回答