c++/cli仅向托管类公开内部成员

本文关键字:内部 成员 cli c++ | 更新日期: 2023-09-27 18:19:32

假设我有一个c++非托管类,它看起来像这个

#include "note.h"
class chord
{
private:
    note* _root;   // or, as in my real class: std::shared_ptr<note> _root;
    // _third, _fifth, _seventh, etc
public:
    someClass(const note n1, const note n2, const note n3);  // constructor takes some of these notes to make a chord
    std::shared_ptr<note> root() const;   // returns ptr to root of the chord
    std::string name() const;  // returns the name of this chord
}

现在,我知道我需要将这两个类封装到cli中的托管类中。但问题是,如何将指向本机类的私有指针传递给构造函数?

目前,Note*_src在noteWrapper中是私有的。但是本机Chord()需要本机Note对象。所以chordWrapper无法访问noteWrappers_src,无法传递给构造函数。在不将内部成员暴露于.net的情况下,我如何才能做到这一点?

编辑**

// assume noteWrapper is already defined, with Note* _src as private
public ref class chordWrapper
{
     private:
     Chord* _src;
     public:
     chordWrapper(noteWrapper^ n1, noteWrapper^ n2, noteWrapper^ n3)
     {
          _src = new Chord(*n1->_src, *n2->_src, *n2->_src); // _src is inaccessible
     }
}

上述操作是不可能的,因为chordWrapper无法访问该内部成员。由于friend也不受支持,我不知道还能做些什么来向.net隐藏内部成员,并将它们公开给cli类。

处理这个问题的合适方法是什么?

c++/cli仅向托管类公开内部成员

内部成员和C++/CLI中的私有成员在同一范围内。它与C#内部修饰符相同。IMHO我认为没有可见性修饰符的类/结构默认情况下会被解释为内部?

public ref class noteWrapper
{
    Note* _src;
}

与在同一范围内

public ref class noteWrapper
{
private:
    Note* _src;
}

但是

public ref class noteWrapper
{
internal:
    Note* _src;
}

是与cli库额外共享的私有成员

您可以使用'internal'关键字仅与cli库共享,而不能与.Net客户端共享。例如

public ref class noteWrapper
{
internal:
    Note* _src;
}