簡體   English   中英

在C ++中使用[]而不是函數調用

[英]Using [] rather than a function call in c++

在課堂上,我們被要求編寫一部分代碼,以使老師編寫的內容生效。 問題是,我無法識別語法。 我問一個朋友,說它可能是重載運算符,但我不知道該在哪里使用。

    templateClass < int > obj(array, arrayS);                   

    cout << obj[1] << endl; 

因此,似乎應該輸出obj數組將保留的插槽1,但是正如我所說,我以前從未見過沒有()和參數的情況。

這會重載[]運算符嗎? 它如何應用於整個對象?

謝謝。

templateClass < int > obj(array, arrayS); int obj(5);的語法相同int obj(5);

這意味着我們要聲明一個對象obj 類型為templateClass<int> ,而初始化方法為arrayarrayS ,它們最終將作為類的構造函數的參數。

obj[1]表示對obj調用重載的operator[] 要查看其實際作用,您將需要查找templateClass的類定義。 (或者,如果應該使obj[1]工作,則需要在templateClass的類定義中編寫一個重載的operator[] )。

以下面的類為例

template <typename T>
class SimpleArray {
public:
    SimpleArray(const T& first_in = T(), const T& second_in = T()) :
        first(first_in), second(second_in) { }

    T& get(int index) {
        return (index == 0) ? (first) : (second);
    }

private:
    T first;
    T second;
};

並假設你有

int main() {
    SimpleArray<int> simple(1,2);
    cout << simple.get(0) << ' ' << simple.get(1) << endl;

    return 0;
}

因此,這只是創建一個類型為'SimpleArray'的對象,並將T作為一個int (將1和2作為其構造函數的參數傳遞。然后,您只需執行get()調用即可在簡單的三元函數的幫助下返回所需的元素現在您可以像這樣重載[]運算符

template <typename T>
class SimpleArray {
public:
    SimpleArray(const T& first_in = T(), const T& second_in = T()) :
        first(first_in), second(second_in) { }

    T& get(int index) {
        return (index == 0) ? (first) : (second);
    }

    T& operator[] (int index) {
        return this->get(index);
    }

private:
    T first;
    T second;
};

並在主測試

int main() {
    SimpleArray<int> simple(1,2);
    cout << simple.get(0) << ' ' << simple.get(1) << endl;
    cout << simple[0] << ' ' << simple[1] << endl;

    return 0;
}

同樣,您每次使用[]語法訪問數組的元素時,只需調用get()函數

我讀這樣的作業:

編寫一個模板類,將接受以下行:

templateClass < int > obj(array, arrayS);
cout << obj[1] << endl;

第一行是構造函數,采用參數,並且int為模板類型,第二行是[]運算符。

但是對模板的功能沒有特殊要求。 換句話說,只要構造函數接受兩個參數(和模板類型為int)並且模板類提供[]運算符,您就可以發揮自己的想象力並實現自己喜歡的任何東西。

查看變量名(數組,arrayS),看來老師希望您傳遞數組和數組的大小。 因此,templateClass的一個想法可能是一個類,該類將c樣式的數組作為輸入並將值存儲在某些c ++容器中。

可以這樣完成:

template <typename T>
class templateClass {
public:
    // Constructor taking array T[] and size as arguments (first requirement)
    templateClass(const T d[], const size_t size)
    {
        for (int i=0; i < size; i++)
        {
            // Copy data from c-style array to a c++ vector 
            mData.push_back(d[i]);
        }
    }

    // [] operator (second requirement)
    T& operator[] (int index)
    {
        if ((index >= mData.size()) || (index < 0))
        {
            // Error - out of range
            // You could throw an exception here or some other error handling
            throw std::invalid_argument( "Invalid index" );
        }
        return mData[index];
    }

private:
    std::vector<T> mData;
};

int main()
{
    try
    {
        int arr[3] = {5, 4, 9};
        templateClass < int > obj(arr, sizeof(arr)/sizeof(arr[0]));

        cout << obj[0] << endl;
        cout << obj[1] << endl;
        cout << obj[2] << endl;

        // Invalid index - will throw exception
        cout << obj[3] << endl;
    }
    catch(...)
    {
        cout << "Exception....";
    }

    return 0;
}

暫無
暫無

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

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