使用结构进行隐式类型转换

Implicit type conversion with structs

本文关键字:类型转换 结构      更新时间:2023-10-16

我是cplusplus的新手,我不知道如何做隐式类型结构之间的转换。

我想执行以下操作:

A a = new __A();
Object o = a;

我知道这需要运算符重载(我认为?机具运算符重载是徒劳的。我使用了本文中的示例:http://www.cplusplus.com/doc/tutorial/typecasting/,但我无法获得任何工作。任何帮助都会非常感激。这是我的结构布局。

typedef __Object* Object;
typedef __Class* Class;
typedef __String* String;
typedef __A* A;
typedef __Test002* Test002;
struct __Object {
  __Object_VT* __vptr;
  // The constructor.
  __Object();
  // The methods implemented by java.lang.Object.
  static int32_t hashCode(Object);
  static bool equals(Object, Object);
  static Class getClass(Object);
  static String toString(Object);
  // The function returning the class object representing
  // java.lang.Object.
  static Class __class();
  // The vtable for java.lang.Object.
  static __Object_VT __vtable;
};
struct __A { 
  __A_VT* __vptr;
  __A();
        static __String* toString(A);
        static int32_t hashCode(Object);
        static bool equals(Object, Object);
        static Class getClass(Object);
  static Class __class();
  static __A_VT __vtable;
};

关于您发布的代码和目标的一些事情

  • C++通过继承为您处理虚拟方法调度,因此无需将虚拟表手动塞入类中
  • 正如其他人所提到的,您正在使用无效/保留的标识符
  • 如果要创建单根继承层次结构(如在 Java 中或添加反射支持之类的内容),那么您可能希望将 Object 类中的所有静态方法重构为虚拟或纯虚拟成员函数,让类 A 公开派生自类 Object 并重写这些方法
  • 您在顶部的用例意味着您真正想要的是能够有一个指向类 A 对象的指针,使用类 Object 的接口:这又是通过 C++ 中的公共继承启用的虚拟调度

所以也许像下面这样

#include <string>
class Object
{
  /* ... */
  public:
    virtual ~Object() = default; // necessary to avoid slicing
    virtual std::string toString() const = 0;
  /* ... */
};
/* virtual inheritance necessary here if you plan on
   deriving from multiple classes that derive from Object;
   otherwise remove */
class A :  public virtual Object 
{
  /* ... */
  public:
    // may or may not be needed, viz., above
    // virtual ~A() = default;
    std::string toString() const override { return std::string{ "A" }; }
  /* ... */
};
#include <iostream>
#include <memory>
int main()
{
  std::unique_ptr<Object> o{ std::make_unique( A ) };
  std::cout << o->toString() << 'n'; // prints "A"
}

里面有很多东西,所以如果你对我写的任何内容感到困惑,请提出问题(尽管它可能会很快跑题)。

为此,__A需要从__Object继承,因为这是将指向前者的指针分配给后者之一的唯一方法。