簡體   English   中英

重載operator()的L值解釋

[英]L-value interpretation of overloading operator()

在學習圖論時,我想嘗試一些代碼,所以我想到了:

class edge
{
public:
    edge(char v1, char v2, int wt = INT_MAX) : vertex1(v1), vertex2(v2), weight(wt) {}

    edge(const edge& e)
    {
        this->vertex1 = e.vertex1;
        this->vertex2 = e.vertex2;
        this->weight = e.weight;
    }

    edge& operator=(const edge& e)
    {
        this->weight = e.weight;
        return *this;
    }

    edge& operator=(const int& w)
    {
        this->weight = w;
        return *this;
    }

    bool operator==(const edge& e) const
    {
        const auto res = this->weight == e.weight;
        return res;
    }

    bool is_connected() const { return !(weight == INT_MAX); }

    char    vertex1;
    char    vertex2;
    int     weight;
};

並對應graph類:

class graph
{
public:
    edge operator ()(const char &i, const char &j) const;  // #1
    edge& operator ()(const char &i, const char &j);  // #2
    // More implementations...

private:
    std::vector<char>   vertices;
    std::vector<edge>   edges;
};

這使我可以編寫如下代碼:

graph g;
g('a', 'b') = 1;
g('a', 'f') = 2;

g('a', 'b') = g('a', 'f');  // #2 is called
g('a', 'b');    // #2 is called

我如何使#1受到呼叫? 好的,我也想到這種結構可能出了點問題。 有人可以幫我檢查一下此代碼嗎? 謝謝! 另外,我在這里閱讀了這篇文章,但是我需要更多信息。

這兩種方法之間的重載分辨率大致等於以下兩個函數的重載分辨率。

edge  func(const graph *thiz, const char &i, const char &j);  // #1
edge& func(graph *thiz, const char &i, const char &j);  // #2

那么以下調用與#2完全匹配,因為第一個參數不是const

graph g;
func(&g, 'a', 'b');

但是,如果第一個參數是const ,則只能調用#1。

如果您想做這種事情,您需要讓operator()返回一個edge_ref幫助對象,該對象可以分配給該對象(以將邊插入圖形中),也可以隱式轉換為edge

class graph {
    std::set<char>                        vertices;
    std::map<std::pair<char, char>, int>  edges;
    class edge_ref {
        graph &self;
        char i, j;
     public:
        edge_ref(graph &g, char i, char j): self(g), i(i), j(j) {}
        int operator=(int weight) {
            self.vertices.insert(i);
            self.vertices.insert(j);
            return self.edges[std::make_pair(i, j)] = weight; }
        operator int() {
            return self.edges.at(std::make_pair(i, j)); }
    };
 public:
    edge_ref operator()(char i, char j) { return edge_ref(*this, i, j); }

暫無
暫無

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

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