使用结构进行隐式类型转换
Implicit type conversion with structs
我是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
继承,因为这是将指向前者的指针分配给后者之一的唯一方法。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 从基本类型转换为非 POD 结构
- 类型转换自定义结构
- 在 c++ 中将结构类型转换为无符号字符*
- C 中STL结构的类型转换
- 继承结构的类型转换导致g++编译错误
- C++基于子类型动态强制转换结构
- 如何将迭代器类型转换为其原始结构
- 使用结构进行隐式类型转换
- 易失性结构与类型转换
- 将字符数组类型转换为结构体(不是类/对象)
- 从字节[]到结构的类型转换
- 将argv类型转换为结构类型
- 将字符缓冲区类型转换为来自套接字的结构
- c++中的类型转换结构
- Boost Fusion:将适应的结构体类型转换为文本
- 使用指针成员对结构体进行类型转换
- 为什么在非指针结构上进行类型转换会出现语法错误
- c++的类型转换结构指针指向类型值