2017-03-07 6 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一時的なインスタンスを作成し、その1は、関数から値によって返されます。

+0

両方のアイデアを完全な文章にリンクして、クリスタルクリアにすることができます。 – Quentin

+0

ありがとうございます。 – gktg1414

関連する問題