簡體   English   中英

我可以通過返回構造函數直接返回對象嗎?

[英]Can I directly return an object by returning constructor?

class time
{
    public:
    time(int i, int j, int k)
    {
        hour = i, minute = j, second = k;
    }

    private:
    int hour, minute, second;
}

time return_an_object_1 (void)
{
    return time(1, 30, 59);  // Using parentheses
}

time return_an_object_2 (void)
{
    return time{1, 30, 59};  // Using curly bracket
}

兩者都可以成功編譯,但是有什么區別?

在這種情況下,是的,它們是相同的,但並非總是如此。 它們可以是同一類的不同構造函數。 在下面的示例中,類的行為根據其構造方式而有所不同:

#include <iostream>
#include <initializer_list>

class Foo {
public:
   Foo( int a, int b, int c) {
      std::cout << "1" << std::endl;
   }

   Foo( std::initializer_list<int> data) {
      std::cout << "2" << std::endl;
   }
};

int main() {
   Foo f(1, 2, 3);
   Foo o{1, 2, 3};
   return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM