我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您通常做的是公开一个返回新对象的公共静态方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
命名在这里,但你明白了.
可以在不需要实例的情况下调用它zippy并创建新zippy对象:
zippy newZippy = zippy::mathematics(42);
Run Code Online (Sandbox Code Playgroud)