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

Is it possible to inherit members as pointers?

本文关键字:指针 继承 成员 是否      更新时间:2023-10-16

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

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

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

我想把它用于SOA(数组结构(。

伪代码:

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];

或者也许我对这个问题的看法不对?

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

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

是否可以将成员作为指针继承?

否。

派生类有一个子对象,它的成员与基类如果不是子对象时的成员完全相同。没有办法影响你从基地获得的成员类型。