C++抛出异常非法

标签 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;

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

这是我尝试做的,但出现了上述错误:

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 illegal use this type as an expression

最佳答案

如果您有类型 ExceptionEmptyOperand,则 throw ExceptionEmptyOperand; 是无效语法。您需要创建一个该类型的对象,然后将其抛出:

throw ExceptionEmptyOperand();

// or
ExceptionEmptyOperand e;
throw e;

关于C++抛出异常非法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794950/

相关文章:

c++ - 从嵌套迭代的列表中删除

c++ - 这个递归函数是如何工作的?合并排序两个单链表

c++ - Windows GDI API 是否在 GetLastError 中返回错误代码?

c - 为什么变量在同一语句中递增后返回以前的值?

c++ - Visual Studio 2019 C++ 无法识别模板 friend

c++ - 最小化广度优先搜索的内存使用

xcode - 无法使用排序函数 swift 找到重载

C++:使用函数重载和 char 到 int 之间的隐式转换,反之亦然

运行时类型解析的 Java 最佳实践

c++ - 重载运算符 '+='