簡體   English   中英

std ::等於用戶定義類的函數

[英]std::equal function with user-defined class

我正在嘗試了解一些示例代碼(請參見下文)。 我對std:equal函數的理解是,當使用用戶定義的類型時,必須定義一個等於==的運算符,以允許該函數執行比較。

所以我不明白這個int()運算符(是否是強制轉換?)如何執行相同的功能。 為什么相等函數會嘗試將A類的實例強制轉換為int?

#include <set>
#include <iostream>
#include <algorithm>
using namespace std;

struct A
{
   int a;

   A(int a) : a(a) {}
   operator int() const { return a; }  //LINE I
};

int main()
{
    set<A> s{ 3, 9, 0, 2, 1, 4, 5, 6, 6, 9, 8, 2 };
    cout << equal(s.begin(), s.end(), s.begin()) << endl;  //LINE II
}

通過查看以下代碼,您可以了解發生了什么:

#include <iostream>


class A {
    public:
        int a;
        A(int a) :    a(a) {}
        //operator int() const {return a;}
};

int main () {

    A a{10};
    A b{20};

    std::cout << std::boolalpha << (a == b) << std::endl; // does not compile
}

如果您注釋轉換運算符,則代碼不進行比較。 如果取消注釋,則代碼將編譯,並且比較是通過將ab隱式轉換為int

之所以執行此轉換,是因為int s的標准運算符==是評估表達式a == b的良好候選者,因此編譯器觸發了對int的隱式轉換(感謝@LightnessRacesinOrbit指出了這一點)。

暫無
暫無

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

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