我正在使用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;
}
答案 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);