首页 > 解决方案 > 是否可以将成员作为指针继承?

问题描述

我想是否可以将成员作为指针继承。

struct base 
{
    int x, y;
};
struct derived : public base 
{   
    // inherit x and y as int pointers
}

只要行为相似,它不必看起来像上面的示例。

我想将它用于 SOA(Structure of Arrays) 。

伪代码:

template<size, return_type, ...traits>
struct Soa<size, return_type, traits...> {
    Soa<size, return_type, traits...>()
    {
        /*
            buld the rdata as something like this
            for(int i = 0; i < size; i++) {
                rdata[i] = {&get<I>(soa_data)[i]...}; 
            }
        */
    }

    second_type : public return_type
    {
        // inherit members as pointers
    }

    return_type &operator[](int i)
    {
        return (return_type &)rdata[i];
    }
    tuple<traits[size]...> soa_data;
    second_type rdata[size];

};
// sample use of the Soa
struct base {
    int x, y;
};
Soa<100, base, int, int> soa; // where the two ints correspond to the members of base
base &b = soa[i];

或者,也许我以错误的方式思考问题?

标签: c++oop

解决方案


无法更改继承变量的类型。但是没有什么可以阻止您创建指向父变量的新变量。

struct base 
{
    int x, y;
};
struct derived : public base 
{
    int *px, *py;
    derived() : px(&x), py(&y)
    {
    }
}

推荐阅读