构造函数返回未命名的对象

时间:2017-03-07 17:50:56

标签: c++

#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 个答案:

答案 0 :(得分:1)

  

有人说它是未命名的对象

正确的术语是临时实例

  

他们中的一些人说它是构造函数。

它实际上是一个构造函数调用。

在变量声明语句之外的构造函数调用将创建Box临时实例,并且该函数将从函数返回值。

相关问题