将构造对象的方法,但不是构造函数

时间:2017-07-24 13:46:52

标签: c++

我正在使用C ++中的不可变结构。假设我想将mathematics移到zippy课程中 - 这可能吗?它构造了一个zippy,但该函数不能是构造函数。它是否必须住在课外?

struct zippy
{
    const int a;
    const int b;
    zippy(int z, int q) : a(z), b(q) {};
};

zippy mathematics(int b)
{
    int r = b + 5;
    //imagine a bunch of complicated math here
    return zippy(b, r);
}

int main()
{
    zippy r = mathematics(3);
    return 0;
}

1 个答案:

答案 0 :(得分:5)

在这种情况下,您通常会公开一个返回新对象的公共静态方法:

struct zippy
{
    static zippy mathematics(int b);
    const int a;
    const int b;
    zippy(int z, int q) : a(z), b(q) {};
};

zippy zippy::mathematics(int b)
{
    int r = b + 5;
    //imagine a bunch of complicated math here
    return zippy(b, r);
}

命名在这里,但你明白了。

可以在不需要zippy的实例的情况下调用它并创建新的zippy对象:

zippy newZippy = zippy::mathematics(42);