簡體   English   中英

如何為顯式重載的構造函數啟用副本初始化?

[英]How to enable copy initialization for explicit overloaded constructor?

我假設使重載的構造函數explicit防止復制初始化,如果我需要explicit進行復制,該如何為以下類啟用復制初始化呢?

class real {
public:
    explicit real(const double& value) : x(value) {}
    real(const real& other) : x(other.x) {}
    ~real() = default;

    real& operator= (const double& rhs) {
        this->x = rhs; 
        return *this;
    }

    operator double() {
        return this->x;
    }
private:
    double x;
};

int main(){

    real r1 = 3.4;  // Error
    real r2 = (real) 3.4;   // Ok : is this the only way ?

    return 0;
}

這不是很好的C ++:

real r2 = (real) 3.4;

您想要的是:

real r2(3.4);

這是將參數傳遞給C ++中的構造函數的常用方法。 這就是人們在閱讀您的代碼時所期望看到的。

如果需要分配,可以執行以下操作:

r2 = real(3.4);

暫無
暫無

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

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