2017-07-24 124 views
0

我正在玩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; 
} 
+3

也許使它成爲'static'成員函數? –

+0

一些挑剔:你不想構建一個類,但你想構造一個類的對象/實例 – user463035818

+0

它可以「活在它的內部」,但它不能依賴調用時'zippy'的有效實例。 – StoryTeller

回答

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); 
+0

喜歡它。真棒。謝謝。 – Carbon