【问题标题】:signature of public member contains native type公共成员的签名包含本机类型
【发布时间】:2014-03-24 23:29:48
【问题描述】:

我是 Visual c++ 的新手,我有以下代码:

ref class Book sealed
{
public:
    Book(std::string title,std::string author,int year);
    void setTitle(std::string title);
    std::string getTitle() const;
    int getYear() const;
    void setYear(int year);
    void setAuthor(std::string author_);
    std::string getAuthor() const;

private:
    std::string title_;
    std::string author_;
    int year_;

};

当我尝试编译它时,我收到以下错误:

{ctor} signature of public member contains native type。我想这是因为我使用的是 std::string 而不是 Platform::String,我该如何解决?

【问题讨论】:

  • 这看起来不像 C++。我认为你需要另一个语言标签。
  • 这是托管 C++,而不是 C++
  • @DavidKernin 对不起,我的错。
  • C++/CLI,微软为.NET平台改编的C++。它不是标准的 C++。
  • 不,它允许这样做。这就是 C++/CX,一种允许 VB.NET 和 Javascript 等语言直接调用 C++ 代码的语言扩展。这当然不能与 std::string 一起使用,Javascript 知道有关该 C++ 类的 bean。

标签: windows-runtime c++-cx


【解决方案1】:

您的 ref 类本身并未标记为公共,因此您似乎只是在内部(作为源)从其他 C++ 使用该类,而不打算将其发布给其他 WinRT 使用者。

如果是这种情况,您可以将您的构造函数设置为internal 而不是public,这将在此组件内公开,在外部不可见。实际上,如果这是您的预期用途,那么它可以只是一个常规的“类”而不是“参考类”。如果您确实希望跨 WinRT 边界使用它但不需要构造函数,则可以将其设为“公共引用类”并将构造函数标记为“内部”。有点取决于您的情况。

如果您希望将此类公开并且有一个可跨 WinRT 边界使用的公共构造函数(以便它可以被 C#/VB/JS 使用),那么您需要使用 WinRT 类型(例如 Platform::String)。在你的类中,存储类型仍然可以是std::string(虽然我建议使用std::wstring,否则你需要进行宽到窄的转换,因为Platform::Strings 是宽字符串)。

要在这两种类型之间进行转换,请使用Platform::String::Data() 来获取底层wchar_t*,您可以使用它来构造std::wstring。同样,Platform::String 有一个构造函数,它接受 wchar_t*(您可以从 std::wstring::c_str() 获取)。

【讨论】:

    【解决方案2】:

    您不能在托管引用类中保存本机类型。

    你只能持有一个指向非托管对象的指针(指针毕竟只是一个数字,这就是它被允许的原因)。

    【讨论】:

      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2020-03-18
      • 2017-12-28
      • 1970-01-01
      相关资源
      最近更新 更多