简体   繁体   English

直接访问struct-within-struct的属性?

[英]Accessing struct-within-struct's properties directly?

I have made tree structs, two of them defined as follows; 我已经制作了树结构,其中两个定义如下:

template < class T, int W, int H >
struct dataRect {
    const int w = W;
    const int h = H;
    const int l = W * H;
    T d[W * H];
};

template < class T >
struct Vec2{
    T x;
    T y;
    // more things
};

And the third one is basically just a struct containing one of each of the previous structs; 第三个基本上只是一个包含前面每个结构之一的结构。

template < class T, int W, int H >
struct xDataRect {
    dataRect<T, W, H> r;
    Vec2<int> p;
};

Now lets say I have an xDataRect xdr, is there a way to make it possible to access the properties of the first two structs directly as 现在说我有一个xDataRect xdr,有没有一种方法可以像下面这样直接访问前两个结构的属性:

xdr.x = 3;

instead of 代替

xdr.p.x = 3;

such that they are perfectly interchangeable? 这样它们就可以完全互换? ((In other words, changing xdr.x changes xdr.p, changing xdr.p changes xdr.x)) ((换句话说,更改xdr.x更改xdr.p,更改xdr.p更改xdr.x))

This is not critical (I can just write xdr.px always), but it would be nice to know if there is a way to do it. 这不是很关键(我总是可以只写xdr.px),但是很高兴知道是否有办法做到这一点。

C++ has inheritance. C ++具有继承性。

It is possible to define Vec2<int> as a base of xDataRect. 可以将Vec2<int>定义为Vec2<int>的基础。 This way .x and .y can be used on a xDataRect object. 这样,.x和.y可以在xDataRect对象上使用。

By overloading xDataRect::operator=(Vec2<int>) it is possible to only set x and y without affecting the other fields. 通过重载xDataRect::operator=(Vec2<int>) ,可以仅设置x和y而不会影响其他字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM