在C++中从内部类对象获取外部类对象
Getting hold of the outer class object from the inner class object in C++
>问题
我在 Java 上看到了这个问题,它允许您从嵌套对象中获取指向外部对象的指针。
但是,如何在C++中实现这一点呢?
不满意的解决方案:
存储指向每个对象的指针:(内存效率不高(
class Outer {
private:
int i;
class Inner {
int j;
Outer *outer;
};
Inner items[1000];
};
将数组包装在类中:(增加不必要的 (?( 复杂性(
class Outer {
private:
int i;
class Inner_array {
class Inner {
int j;
};
Inner items[1000];
// Build an interface around the array
typedef Inner (&array)[1000];
operator array();
// etc...
};
Inner items[1000];
Outer *outer;
};
这里有一个节省空间的想法:
struct Outer {
int i;
struct Inner {
int j;
uint16_t where;
Outer& outer() {
Inner* first = this - where;
char* addr = reinterpret_cast<char*>(first) - offsetof(Outer, items);
return *reinterpret_cast<Outer*>(addr);
}
};
Inner items[1000];
Outer() {
for (uint16_t ii = 0; ii < 1000; ++ii)
items[ii].where = ii;
}
};
如果你使用的是具有 32 位整数的 64 位计算机,这会将sizeof(Inner)
从 16 个字节减少到 8 个字节(不打包(或 12 到 6 个字节(不打包(。
如果你想节省更多的空间,你可以这样做:
struct Outer {
int i;
struct Inner {
int j;
Outer& outer() {
Inner* sentinel = this;
while (sentinel.j != INT_MIN)
--sentinel;
char* addr = reinterpret_cast<char*>(sentinel) - offsetof(Outer, sentinel);
return *reinterpret_cast<Outer*>(addr);
}
};
Inner sentinel = {INT_MIN};
Inner items[1000];
};
但是outer()
是 O(n( 而不是 O(1(,您必须确保INT_MIN
(或某些哨兵值(永远不会在items
中使用。
相关文章:
- 如何在C++中获取该对象的类声明中对象的地址?
- 无法获取webot::PositionSensor对象中位置传感器的值
- 最多获取2个对象
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 如何在新的派生对象中获取基本对象的数据?
- 如何从 CSV 获取数据并将其存储在 C++ 中的表对象中
- 数组中不同类型的对象并获取每个对象的类型
- push_back通过自行创建的对象获取最后一个元素的向量
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 在C++中从内部类对象获取外部类对象
- 如何从 GDI+ 图元文件对象获取原始图元文件字节
- C++ std::队列推送弹出两个不同的对象获取第一个对象
- 尝试从另一个类对象获取值时出现分段错误
- 从元对象获取属性更改通知程序
- 从 Json 对象获取非缩进字符串
- 从套接字对象获取fd或句柄
- (如何)我可以从IWbemClassObject对象获取GUID吗
- 使用不同类中的类对象获取不正确的数据
- OpenCV Mat 对象 - 获取数据长度
- 在 c++ 中,如何从对象获取到静态成员