簡體   English   中英

如何通過繼承實現移動構造函數和移動賦值運算符(抽象基類)

[英]How to implement move constructor and move assignment operator with inheritance(abstract base class)

我得到的Visual Studio中的錯誤消息是我正在學習c ++,並想測試一些東西。 我使用Account(作為抽象基類)和JointAccount(具有從Account的公共繼承)創建了一個帳戶層次結構。 但是我不知道如何為JointAccount實現復制構造函數和復制賦值運算符。 我嘗試了一些嘗試,但沒有成功。 我搜索了,但沒有明確的解釋。

class Account : public Printable
{
protected:
    std::string* name;
    double balance;

public:
    Account(std::string name, double balance);
    Account(const Account& source);
    Account(Account&& source);
    virtual ~Account();
    Account& operator=(const Account& rhs);
    Account& operator=(Account&& rhs);
    .
    .
    .
    virtual void print(std::ostream& os) const override = 0;
};
Account::Account(Account&& source)
    :   name{source.name}, balance{source.balance}
{
    source.name = nullptr;
}

Account& Account::operator=(Account&& rhs)
{
    this->name = rhs.name;
    this->balance = rhs.balance;
    rhs.name = nullptr;
    return *this;
}
class JointAccount final : public Account
{
private:
    std::string* secondName;
public:
    JointAccount(std::string name, double balance, std::string secondName);
    JointAccount(const JointAccount& source);
    JointAccount(JointAccount&& source);
    virtual ~JointAccount();
    JointAccount& operator=(const JointAccount& rhs);
    JointAccount& operator=(JointAccount&& rhs);
    .
    .
    .
    virtual void print(std::ostream& os) const override;
};
I tried this but it does not work as Account is Abstract VVV

JointAccount::JointAccount(JointAccount&& source)
    :   Account{source}, secondName{source.secondName}
{
    ?
}

And as I can't figure out the move constructor, I also can't figure 
out how to do the move assignment operator VVV

JointAccount& JointAccount::operator=(JointAccount&& rhs)
{
    ?
}

這是我認為您嘗試正確編譯的基本示例: https : //coliru.stacked-crooked.com/a/8a5b64904f262b5a

我懷疑您的問題未能定義要聲明為虛擬的函數。 解決方案是確保定義了所有非純虛擬方法。 請注意,即使已聲明析構函數是純虛擬的,也必須對其進行定義。

您嘗試的基本結構似乎是有效的,因此您的問題似乎在實現的其他地方。

暫無
暫無

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

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