c++ - 使用结构的隐式类型转换

标签 c++ types typecasting-operator

我是 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++ 通过继承为您处理虚拟方法分派(dispatch),因此无需将虚拟表手动插入您的类
  • 正如其他人提到的,您使用的是无效/保留的标识符
  • 如果您正在创建一个单根继承层次结构(如在 Java 中或添加反射支持之类的东西),那么您可能希望将 Object 类中的所有静态方法重构为虚拟或纯虚拟成员函数,具有 class公开派生自类 Object 并重写这些方法
  • 你在顶部的用例暗示你真正想要的是能够有一个指向类 A 的对象的指针使用类 Object 的接口(interface):这又是通过 C++ 中的公共(public)继承启用的虚拟分派(dispatch)

所以也许像下面这样

#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"
}

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

关于c++ - 使用结构的隐式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27158660/

相关文章:

c++ - 函数参数前的类关键字是什么?

haskell - 类型 (.) 。 (.)

C : Segmentation fault with typecasting

c++ - 你如何实现相互转换?

c++ - C++ 中的哈希表与 STL 映射

c++ - 删除 vector 而不删除数组

c++ - 如何通过现有的静态数组初始化 C 风格结构中的静态数组?

Android RenderScript Matrix_2x2 元素数据类型

sql - Oracle:在 PostgreSQL 中有与 ROW 等价的东西吗?

python - 在 python 中将 numpy 矩阵类型转换为字符串