【发布时间】:2013-06-22 05:47:52
【问题描述】:
假设我有一个像这样的 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类。
处理这个问题的适当方法是什么?
【问题讨论】:
-
您可以通过创建一个与本机类具有相同成员的 ref 类来创建包装器。所以你的 chordWrapper 还应该有一个构造函数,它接受三个 noteWrapper 参数。你应该有一个 noteWrapper 类型的 root 字段,使 getter 变得微不足道。
-
这里的问题是指向类的指针(注意,和弦)是私有的,仅供cli类内部使用。但是 cliChord 类需要以某种方式访问 cliNotes 私有指针,以传递给本机 chord 构造函数。如果不将指针设置为公共,这可能吗?
-
C++ 标准,也适用于 C++/CLI,使用 friend 关键字。