我使用命名构造函数惯用语来创建对象,因为我有很多调用都具有相同的参数,但是对象应该以不同的方式创建。
C ++ FAQ告诉我们如何做到这一点。它还告诉我们如何强制对象在堆上分配。然而,它确实没有告诉我们如何使用new运算符与命名构造函数惯用语。
因为new需要调用构造函数,我们不能直接调用命名构造函数。所以,我找到了两个解决这个问题的方法:
我创建了一个额外的复制构造函数,并希望优化编译器不会创建临时对象。
因为new需要调用构造函数,我们不能直接调用命名构造函数。所以,我找到了两个解决这个问题的方法:
我创建了一个额外的复制构造函数,并希望优化编译器不会创建临时对象。
class point_t {
int X,Y;
point_t(int x, int y) : X(x), Y(y) { }
public:
point_t(const point_t &x) : X(x.X), Y(x.Y) { }
static point_t carthesian(int x, int y) { return point_t(x,y); }
static point_t polar(float radius, float angle) {
return point_t(radius*std::cos(angle), radius*std::sin(angle));
}
void add(int x, int y) { X += x; Y += y; }
};
int main(int argc, char **argv) {
/* XXX: hope that compiler doesn't create a temporary */
point_t *x = new point_t(point_t::carthesian(1,2));
x->add(1,2);
}
另一种版本是创建单独的命名构造函数。由于函数重载不适用于返回类型,我使用了两个不同的名称,这很丑陋。
class point_t {
int X,Y;
point_t(int x, int y) : X(x), Y(y) { }
public:
/* XXX: function overloading doesn't work on return types */
static point_t carthesian(int x, int y) { return point_t(x,y); }
static point_t *carthesian_heap(int x, int y) { return new point_t(x,y); }
void add(int x, int y) { X += x; Y += y; }
};
int main(int argc, char **argv) {
point_t *x = point_t::carthesian_heap(1,2);
x->add(1,2);
}
有没有一个更美观的版本与示例代码相等?