【发布时间】:2019-02-15 18:56:21
【问题描述】:
struct Foo
{
union {
struct { int a, b; };
int index[2];
};
};
struct Bar : public Foo
{
union {
// Foo members
struct { int barA, barB; };
};
};
int main()
{
Foo f;
Bar b;
// I want it so that
&b.a == &b.barA;
// in the same way that
&f.a == &f.index[0];
}
有什么办法可以让 Bar 的成员与其父类“联合化”?
非常感谢,非常感谢任何帮助
编辑: 这是所要求的用例:
struct Vec2
{
union {
float index[2];
struct { float x, y; };
};
Vec2(float xVal, float yVal)
: x(xVal), y(yVal)
{
}
~Vec2() {}
Vec2 & add(const Vec2 & b) { /* implimentation */ }
Vec2 & sub(const Vec2 & b) { /* implimentation */ }
};
struct ComplexNumber : public Vec2
{
union {
// Vec2 members
struct { float real, imag; };
};
ComplexNumber(float realPart, float imagPart)
: real(realPart), imag(imagPart)
{
}
ComplexNumber & mul(const ComplexNumber & b) { /* implimentation */ }
ComplexNumber & div(const ComplexNumber & b) { /* implimentation */ }
};
int main()
{
ComplexNumber a(5, 2);
ComplexNumber b(7, 8);
}
我希望不仅能够解决 a 和 b 的 Vec2 成员, 但也可以使用 Vec2 中声明的函数,甚至可能添加 ComplexNumbers 和 Vec2s 可以互换。
【问题讨论】:
-
Bar 是否必须从 Foo 继承 (is-a),还是可以包含 (has-a) Foo?
-
struct { int a, b; };是一个匿名结构成员。 C++ 中不允许使用匿名结构。 -
这是一个巧妙的问题。我可以看到为什么它应该被禁止的很多原因,派生类不能改变基类的大小,但是如果大小没有改变,是否有足够的用例来注入允许的异常是否纳入标准?
-
建议:Gabe,如果这不仅仅是出于学术目的,请将您的用例添加到问题中。有人可能会给你一个解决方法或替代方案。
-
以什么方式禁止“struct {int a, b;}”?我正在使用 g++ 编译并启用所有警告,但没有得到任何警告。
标签: c++ oop inheritance struct unions