【发布时间】:2013-07-15 22:09:25
【问题描述】:
在 C++ 中,我经常(几乎总是)遇到构造函数的问题;我永远不确定如何使用参数,最终我将最终只为每个类使用无参数构造函数。 然后我将在每个实例定义之后使用 setter。 例如:
// Obviously better
Point p(5, 3);
// ...and yet I end up using this
Point p;
p.setX(5);
p.setY(3);
我最终使用“更糟糕”的方法的原因是因为有些类需要太多参数,并且有太多不同的可能性来构造它们,所以我的想法变得一团糟,我不再知道我应该做什么。 这是我最近制作的一个类的示例(它使用 Qt):
// implements position and pixmap (image shown when painted)
class Block : QObject {
public:
Block(const QPixmap &img = Pixmap(), QObject *parent = 0);
Block(const QPoint &pos, const QPixmap &img = Pixmap(), QObject *parent = 0);
Block(int x, int y, const QPixmap &img = Pixmap(), QObject *parent = 0);
Block(const Block &other);
};
只有一个只有两个属性的类(position 和image),我已经有四个构造函数最多接受四个参数。
另外,我经常看到人们用Block(QObject *parent = 0); 和Block(const QPixmap &img, QObject *parent = 0); 替换第一个构造函数,我不确定这是否是一件好事。
现在,如果我创建一个自己的 Rectangle 类,它继承自 Block,所以它还需要采用 image 和 position 作为参数:
Rect(const QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(const QRect &rect, const QPixmap &pixmap = QPixmap(), QObject *parent = 0);
Rect(const QSize &size, const QPoint &pos = QPoint(), const QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(const QPoint &pos, const QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(int x, int y, int w = 1, int h = 1, QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(int w, int h, QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(const QPoint &pos, int w, int h, QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(int x, int y, const QSize &size, QPixmap &img = QPixmap(), QObject *parent = 0);
Rect(const Rect &rect);
如您所见,它开始看起来很糟糕,而且很难维护。
想象一下Player 类继承自Rect 并实现items、health、mana、damage、armor...
我发现编写这样的构造函数是不可能的。
既然我已经给了你这个问题,我不确定这个问题;我需要任何提示或技巧来帮助我使用构造函数、何时使用默认参数以及我需要所有构造函数的频率,是的,只是一些技巧可以防止我为一个类创建 500 个构造函数;我应该使用我原来的p.setX(5); 示例吗?
【问题讨论】:
-
您是在这里创建自己的类还是使用库中的类?
-
@MonadNewb 以
Q开头的类来自 Qt 库,其余的是我的。 -
我不同意结束这个问题。诚然,有许多选项可用于解决 OPs 问题,并且在许多情况下,选择主要基于意见。但是,可以在一个相当简洁的答案中列举潜在的解决方案,以及给出每种解决方案的优缺点的资源。为了对这些选项有意见,首先必须知道存在哪些选项。提供这些工具并不违背针对基于意见的问题的 SO 规则的精神,IMO。
标签: c++ constructor overriding class-hierarchy