2017-03-07 51 views
0
#include <iostream> 

using namespace std; 

class Box { 

    friend Box operator+(Box &box1, Box &box2); 
public: 

    Box(int L, int H, int W) 
     :length(L), height(H), width(W) { 
     cout << "\nBox constructor is executed"; 
    } 

    void display() { 
     cout << "\nLength = " << length; 
     cout << "\nHeight = " << height; 
     cout << "\nWidth = " << width; 
    } 

private: 
    int length; 
    int height; 
    int width; 
}; 

Box operator+(Box &box1, Box &box2) { 
    cout << "\nFriend add operator is executed"; 

    int L = box1.length + box2.length; 
    int H = box1.height + box2.height; 
    int W = box1.width + box2.width; 

    return Box(L, H , W); 
} 

int main() { 
    Box firstBox(4, 5, 6); 
    Box secondBox(3, 3 ,3); 

    firstBox.display(); 
    firstBox = firstBox + secondBox; 
    firstBox.display(); 

    return 0; 
} 

我找到了一個代碼來理解朋友函數。我明白了。但是,我不明白朋友操作員返回什麼?有人說這是未命名的對象。其中一些人說它是構造函數。他們兩人聽起來不合理。請有人解釋一下嗎?構造函數返回未命名對象

回答

1

有人說,它是未命名的對象

,正確的說法是臨時實例

其中有些人說它是構造函數。

它實際上是一個構造函數調用。

變量聲明語句之外的構造函數調用將創建一個臨時實例Box,並且該值是從該函數返回的值。

+0

您可能想將兩個想法鏈接到一個完整的句子,所以它很清楚:) – Quentin

+0

非常感謝。 – gktg1414

相關問題