簡體   English   中英

重載運算符 [ ] 以在下標位置返回 integer。如果作為索引傳遞的數據類型錯誤,則使用 c++ 進行異常處理

[英]Overload operator [ ] to return the integer at subscript location.If values of wrong data type passed as index ,handle by exception using c++

如果索引值為 integer 那么它將返回相應的值。 如果索引值是浮點數,那么它將拋出一個錯誤,該錯誤將由異常處理,這樣錯誤數據類型的值就不會作為索引傳遞; 如果通過,它將被異常處理。 當我訪問 A[f] 它應該由異常處理,但它顯示編譯時錯誤(無效類型 char[10[float] 數組下標)

class Vector {
    char A[10];

public:
    char operator[](int i)
    {
        return A[i];
    }
    float operator[](float i)
    {
        throw i;
    }
    void get()
    {
        ..
    } //To get the string input
    void Display()
    {
        float f = 1.0;
        cout << A[f];
    };
    int main()
    { //Vector v;
        try {
            v.Display(); //What should I change in this code
        }
        catch (float i) {
        }
    }
cout << A[f];

A是一個char數組,它的[]運算符當然不能采用浮點索引。

您顯然打算調用這個類的operator[]重載,它與數組沒有直接關系,無論如何:

cout << (*this)[f];

這是一些我認為您正在嘗試做的代碼。

請注意,如果要調用 operator[] 函數,則需要在class 類型的 object上使用 [] ,而不是在普通數組上使用。 我在主 function 中添加了另一行,以展示如何在 Vector object 上使用 []。

如果您確實想在 class object 上使用 [] 從 ZA2F2ED4F8EBC0thisAB61DZ 內部的 function 使用 [],那么您需要使用 (*thisAB61DZ)。

class Vector {
    char A[10];
public:
    char operator [](int i)
    {
        return A[i];
    }
    float operator [](float i)
    {
        throw i;
    }
    void get()
    {

    }//To get the string input
    void Display()
    {
        float f = 1.0;
        cout << (*this)[f];
    };
    
};

int main()
{
    Vector v;
    try {
        v.Display();// Throws an exception
        v[1.0f];   //  This is how you call the operator[] functions. 
    }
    catch (float i) {
        cout << "exception" << endl;
    }
}

暫無
暫無

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

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