c++ - 指向抽象类的指针

标签 c++ c++-cli abstract-class

我正在尝试使用 c++/cli 包装非托管 c++ 代码。在 C++/cli 中,如果类具有所有纯虚 函数,则必须将其声明为抽象。现在假设我有以下 C++ 代码:

class A{
public:
  virtual ~A();
  virtual void foo() = 0;
  virtual void boo() = 0;
  virtual void goo() = 0;
};
inline
A::~A()
{
}

class B
{
public:
  B();
  A* getA() const;
};

inline A* B::getA() const
{
  //do something
  return (A *) //of something;
}

按照上面我可以返回 A* 而没有任何错误。现在假设我将上面的代码包装如下:

public ref class manA abstract 
{
public:
  manA(A*);
  virtual ~manA();
  virtual void Foo() = 0;
  virtual void Boo() = 0;
  virtual void Goo() = 0;
private:
  A* m_A;
};

inline
manA::~manA()
{
}

inline
manA::manA(A*)
{
  //data marshalling to convert A* to manA
}

public ref class manB
{
public:
  manB();
  manA ^ GetA();
private:
  B * m_B;
};

inline manB::manB()
{
  m_B = new B;
}

inline manA ^ manB::GetA()
{
  A *value = m_B->getA();
  return gcnew manA(value);
}

现在,如果我执行上述操作,我会得到一个无法实例化声明为“抽象”的类错误。

有什么解决办法吗?

注意:类 A 为其所有可能的实现定义了接口(interface)。那么也许有一种方法可以定义 manA,使其不是抽象的,因此可以实例化?

我找到了解决问题的办法:

manA 中删除构造函数并使用属性

public:
property A* UnmanagedObject 
{
  void set(A* unmanagedObjPtr)
  {
    //Or other data marshalling
    m_A = (A *)(unmanagedObjPtr);
  }
}

在 manB 内部做:

inline manA ^ manB::GetA()
{
  A *value = m_B->getA();
  manA ^ final;
  final->UnmanagedObject  = value;
  return final;
}

最佳答案

编写包装器并不意味着编写相同的本地类。不要将 manA 设为抽象类,问题就迎刃而解了。

public ref class manA abstract 
{
public:
  manA(A*);
  virtual ~manA();
  virtual Foo() { m_A->foo(); } 
  virtual Boo() { m_A->boo(); }
  virtual Goo() { m_A->goo(); }
//Also there should be an error like "Hey, What is the return type of those functions?"
//"virtual void Foo()" or "virtual int Foo()" or something else
private:
  A* m_A;
};

关于c++ - 指向抽象类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7426512/

相关文章:

java - 调用抽象类@Activate方法(apache felix)

c++ - 为什么我们需要 C++ 中的抽象类?

java - 有没有办法在 Java 中实现代数类型?

c++ - 带有模板 C++ 的嵌套类

c++ - 关于get line和string find函数的问题

C++对象[实现]运算符==错误

c++ - Visual Studio Code 以类似 NetBeans 的方式远程调试 c++

C# 到 C++/CLI 到 C DLL System.IO.FileNotFoundException

c++ - 从一个 C++ 程序中调用另一个程序中的方法(进程间通信)

c++ - 无法将参数 2 从 'mxArray **' 转换为 'mwArray &'