簡體   English   中英

這兩種調用基類復制賦值方法有什么區別?

[英]What is the difference between these two ways to invoke base class copy assignment?

假設我有以下內容:

class A
{
public:
    A& operator= (A const& other)
    {
        return *this;
    }
};

class B : public A
{
public:
    B& operator= (B const& other)
    {
        static_cast<A&>(*this) = static_cast<A const&>(other);
        // or...
        A::operator=(other);
        return *this;
    }
};

要調用A的副本分配運算符的版本,我可以執行以下任一操作:

static_cast<A&>(*this) = static_cast<A const&>(other);

要么:

A::operator=(other);

你為什么選擇一個而不是另一個? 兩者有什么不同?

編輯

我的問題的最初示例是無效的,並且與我要問的問題相去甚遠。 我為這個錯誤道歉。 我已經更新了上面的例子,以便更清楚。

static_cast<A&>(*this).foo()仍調用foo的派生版本。 這只是通過基類引用調用虛函數。

A::foo()關閉虛擬調度並調用在類A實現的foo ,而不是在派生類中。


如果operator=不是虛在Astatic_cast<A&>(*this) = static_cast<A const&>(other)是另一種說法A::operator=(other) (無需上溯造型other因為派生到基參考轉換是隱式的)。 他們做同樣的事情-調用A::operator=

通常, operator=是根據copy構造函數實現的,后跟swap:

B& B::operator=(B other) { 
    other.swap(*this); 
    return *this;
}

按值取B為我們調用B的副本構造函數。 如果B具有r值復制構造函數,則該賦值運算符可與r值以及僅移動B (例如,如果B具有std::unique_ptr成員)。

如果你想要兩個類(A和B)的A賦值運算符,只是不要在B類中實現它。

暫無
暫無

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

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