将运算符 [ ] 重载到 return 下标处的整数 location.If 错误数据类型的值作为索引传递,使用 C++ 进行异常处理

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

如果索引值是整数那么它将return相应的值。如果索引值为浮点数,那么它将抛出一个错误,该错误将由异常处理,这样错误数据类型的值就不会作为索引传递;如果通过,它将被异常处理。 当我访问 A[f] 时,它应该由异常处理,但它显示编译时错误 (invalid types char[10[float] array subscript)

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数组,它的[]运算符当然不能取浮点索引。

您显然是想调用此 class 的 operator[] 重载 ,它与直接无关与阵列,无论如何:

cout << (*this)[f];

这是一些代码,可以执行我认为您正在尝试执行的操作。

请注意,如果要调用 operator[] 函数,则需要在 类型为 class 的对象上使用 [],而不是在普通数组上。我在您的 main 函数中添加了另一行来展示如何在 Vector 对象上使用 []。

如果您确实想通过 class 中的函数在 class 对象上使用 [],那么您需要使用 (*this)[].

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;
    }
}