C++/CLI:是否只能重载返回类型?

发布于 2024-09-17 18:28:59 字数 408 浏览 3 评论 0原文

如果我理解得很好,在 C# 中,可以

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

按照 this 进行操作线程。这种重载在 C++ 中是被禁止的,因为它仅取决于返回类型。

现在,我想在 C++/CLI 中使用 ICloneable 来完成这件事。有办法吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帅气尐潴 2024-09-24 18:28:59

C# 中允许这种类型的重载,不是因为返回类型不同,而是因为接口 - ICloneable.Clone 的显式实现。

关于 C++/CLI 看这里: http://msdn .microsoft.com/en-us/library/ms235235%28VS.80%29.aspx

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

凉宸 2024-09-24 18:28:59

我终于找到了一个办法:

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); }

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); }
梦与时光遇 2024-09-24 18:28:59

在 C++ 中,您可以省略第二行,C++ 允许重写中的协变。由于X Clone()object ICloneable::Clone()的约定兼容,因此它可以将其直接放入v表中,而不需要转发函数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文