簡體   English   中英

C ++:可以使用具有相同參數的私有構造函數重載構造函數嗎?

[英]C++: Can one overload a constructor with a private constructor with the same parameters?

可以使用具有相同參數的私有構造函數重載構造函數嗎?

基本上,如果某些東西存儲正整數,那么在公共構造函數中它將確保存儲正整數,而在私有構造函數中它不執行檢查。

顯然,這個例子並不是一個合適的用法,但有時你想在一個方法中創建一個對象,你不希望它浪費時間進行完全安全的初始化; 您可能只想告訴它在沒有特殊檢查的情況下立即創建一些東西(或者更謹慎的堆分配或者更昂貴的東西),當您稍后再次執行它們或者它們只是不必要時,類中的方法應該是能夠自動使用此構造函數而不是具有相同參數的其他公共構造函數。

不,您不能使用私有構造函數或其他成員函數重載:只有名稱和參數類型才能用於重載解析。

要執行您要查找的內容,請定義一個私有構造函數,該構造函數接受一個額外的bool參數,該參數指示需要執行參數檢查:

class A {
public:
    A(int x) : A(x, true) {}
private:
    A(int x, bool check) {
        if (check) {
            // Perform the check of the x argument
        }
    }
};

構造實例並繞過檢查,可以訪問私有構造函數調用的函數

A aUnchecked(-123, false);

檢查實例以通常的方式構造:

A aChecked(123);

您不能像私有對象那樣超載acccess,但是您可以重載簽名:參數的數量及其類型。

私人建築師很常見。

一種用法是邏輯上“刪除”的構造函數(最后由C ++ 11直接支持),另一種用於公共工廠函數。


例:

class A
{
public:
    A( int const x)
    {
        // Whatever, checked construction.
        // Perform the check of the x argument.
        // Then other things.
        // In C++11 it can be done by checking x and forwarding to the
        // unchecked constructor in the same class. Not shown here though.
    }

private:
    enum unchecked_t { unchecked };
    A( int const x, unchecked_t )
    {
        // Unchecked construction.
    }

    // Methods that possibly use the unchecked constructor.
};

使用私有構造函數,你不能直接實例化一個類,而是使用一個名為Constructor Idiom的東西。

你不能繼承該類的其他東西,因為想要繼承的類將無法訪問構造函數

你應該做的就是從構造函數中調用來檢查a aththode

暫無
暫無

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

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