创建派生类作为超类的子集

发布于 2025-01-25 15:55:41 字数 1394 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何处潇湘 2025-02-01 15:55:41

哪个有效,但这是最好的方法吗?有更好的方法可以实现什么吗
我想要?

最好的方法取决于您打算如何使用Point2d

如果您真的想要point2dmatrix< 3,1>是相同的,那么一种可能的方法是制作point2d类型别名并写入Make函数来创建它:

using Point2D = Matrix<3, 1>;
Point2D make_point_2d(float x, float y) { return Point2D{x, y, 1}; }

int main() {
    auto const a = make_point_2d(-1, 1);
    Matrix<3, 3> translate = {1, 0, 2, 0, 1, -2, 0, 0, 1};

    Point2D out = translate * a;
}

为了保持设计一致,我会介绍类型的别名和Make _**其他类型的功能。例如:

using Matrix3x3 = Matrix<3,3>;
Matrix3x3 make_matrix_3x3(/* ... */) { /*...*/ }

只要您需要引入的类型别名并不多于太多,这可能会起作用。


编辑:我不确定point2d be(或公开继承)
矩阵&lt; 3,1&gt;是个好主意。作为用户,我会对这个事实感到惊讶
此代码将编译(并且运行而不会导致任何断言失败):

auto const a = make_point_2d(-1, 1);
a(2,0);

// 1. Why do I need the second index to access the elements of a Point2D?
// 2. Why can I access the element at index 2?

Which works, but is this the best way? Is there a better way to achieve what
I want?

The best way depends on how you intend to use your Point2D.

If you really want Point2D and Matrix<3,1> to be the same, a possible approach is to make Point2D a type alias and write a make function to create it:

using Point2D = Matrix<3, 1>;
Point2D make_point_2d(float x, float y) { return Point2D{x, y, 1}; }

int main() {
    auto const a = make_point_2d(-1, 1);
    Matrix<3, 3> translate = {1, 0, 2, 0, 1, -2, 0, 0, 1};

    Point2D out = translate * a;
}

To keep the design consistent, I'd introduce type aliases and make_* functions for other types too. E.g.:

using Matrix3x3 = Matrix<3,3>;
Matrix3x3 make_matrix_3x3(/* ... */) { /*...*/ }

This may work as long as the type aliases you need to introduce are not too many.


Edit: I'm not really sure having Point2D be (or publicly inherit from)
Matrix<3,1> is a good idea. As a user, I'd be quite surprised by the fact
this code would compile (and run without causing any assert to fail):

auto const a = make_point_2d(-1, 1);
a(2,0);

// 1. Why do I need the second index to access the elements of a Point2D?
// 2. Why can I access the element at index 2?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文