c++临时对象创建了吗?

标签 c++ object constructor function-call

我想知道这段代码是如何工作的。

class Room
{
    int sqft;
public:
    Room(int k)
    {
        sqft = k;
    }
    int add(Room r)
    {
        return r.sqft + sqft;
    }
};
int main()
{
    Room living = Room(400);
    Room Kitchen = Room(250);
    Room Bedroom = Room(300);
    int total = living.add(Kitchen.add(Bedroom)); // ***
    cout << total << endl;

    system("pause");
    return 0;
}

带星号的行正在调用 Room 类中的 add 函数。但是在 Kitchen.add(Bedroom) 之后返回的类型是一个 int。没有将 int 作为参数的添加函数,所以我预计代码会出错。我认为这条线需要是:

int total = living.add(Room(Kitchen.add(Bedroom)));

这确实也有效,我只是不明白它是如何工作的,只是将 int 传递给 add 因为这一行也有效:

cout << living.add(10);

看起来好像因为 Room 采用了一个 int 构造函数,所以 c++ 知道如何将一个 int 隐式转换为一个 Room。这是真的?幕后的 C++ 中发生了什么?

最佳答案

是的,这是真的,因为您声明了一个带有 int 参数的构造函数,编译器将隐式地将 int 转换为 Room

您通过将构造函数声明为显式来修复此问题,然后编译器将不再进行隐式转换,而是要求您像在示例中那样显式调用构造函数。

  explicit Room(int k)
//^^^^^^^^
{
    sqft = k;
}

Room Bedroom = Room(300);                       // still works
int total = living.add(Kitchen.add(Bedroom));   // gives compile error
total = living.add(Room(Kitchen.add(Bedroom))); // works

关于c++临时对象创建了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40115290/

相关文章:

php - `clone` 比在 PHP 中实例化新对象有什么优势?

javascript - 哪个版本的 javascript 引入了任意构造函数返回?

java - 无法使用 Class.forName() 实例化类

java - 在 Haxe 中检测目标语言

c++ - 初始化 STL `map` 大小

c++ - 将创建的对象分配给选定的对象

python - 将字典传递给构造函数?

c++ MS Word - OleAutomation 收藏

c++ - gtkmm:窗口内的模态小部件

function - Dart 访问作为对象。如何调用它们?