C ++抛出异常非法

时间:2016-01-14 16:39:46

标签: c++ overloading operator-keyword

获取错误:非法使用此类型名称 这是operator+重载:

    template<class T>
        inline Vec<T> Vec<T>::operator+(const Vec& rhs) const
        {
            int vecSize = 0;
            if (rhs.size() == 0 || size() == 0) {
                throw ExceptionEmptyOperand;
            }
            if (rhs.size() != size()) {
                throw ExceptionWrongDimensions;
            }
            else
            {
                Vec<T> vec;
                vecSize = rhs.size();
                for (int i = 0; i < vecSize;i++) {
                    vec.push(*this[i] + rhs[i])
            }

return vec;
        }

这是operator[]重载的声明:

  T& operator[](unsigned int ind);
    const T& operator[](unsigned int ind) const;

第一个是为了能够改变矢量值。

这是我尝试做的并且如上所述收到错误:

template<class T>
inline T& Vec<T>::operator[](unsigned int ind) 
{
    list<T>::iterator it = vals_.begin();
    if (size() == 0) {
        throw ExceptionEmptyOperand;
    }
    if (size() < ind) {
        throw ExceptionIndexExceed;
    }


    for (unsigned int i = 0; i<ind; i++) {
            ++it;
        }
        return *it;
    }

它给了我这个错误:ExceptionEmptyOperand非法使用此类型作为表达式

2 个答案:

答案 0 :(得分:1)

如果您的类型为ExceptionEmptyOperand,则throw ExceptionEmptyOperand;语法无效。您需要创建该类型的对象然后抛出它:

throw ExceptionEmptyOperand();

// or
ExceptionEmptyOperand e;
throw e;

答案 1 :(得分:0)

template<class T>
    inline Vec<T> Vec<T>::operator+(const Vec& rhs) const
    {
        int vecSize = 0;
        if (rhs.size() == 0 || size() == 0) {
            throw ExceptionEmptyOperand;
        }
        if (rhs.size() != size()) {
            throw ExceptionWrongDimensions;
        }
        Vec<T> vec;
        vecSize = rhs.size();
        for (int i = 0; i < vecSize;i++) {
            vec.push((*this)[i] + rhs[i])
        return vec;
    }


template<class T>
inline T& Vec<T>::operator[](unsigned int ind) 
{
    if (size() == 0) {
        throw ExceptionEmptyOperand;
    }
    if (size() <= ind) {
        throw ExceptionIndexExceed;
    }

    list<T>::iterator it = vals_.begin();
    for (unsigned int i = 0; i<ind; i++) {
            ++it;
    }
    return *it;
}

template<class T>
inline const T& Vec<T>::operator[](unsigned int ind) const
{
    if (size() == 0) {
        throw ExceptionEmptyOperand;
    }
    if (size() <= ind) {
        throw ExceptionIndexExceed;
    }
    list<T>::const_iterator it = vals_.begin();

    for (unsigned int i = 0; i<ind; i++) {
        ++it;
    }
    return *it;
}